首页 文章

如何运行PowerShell脚本

提问于
浏览
569

如何运行PowerShell脚本?

  • 我有一个名为myscript.ps1的脚本

  • 我安装了所有必要的框架

  • 我设置了execution policy的东西

  • 我已按照this MSDN help page上的说明进行操作,并尝试按以下方式运行: powershell.exe 'C:\my_path\yada_yada\run_import_script.ps1' (有或没有 --noexit

除了输出文件名外,它什么都不返回 .

没有错误,没有消息,没有 . 哦,当我添加 -noexit 时,同样的事情发生了,但我仍然在PowerShell中并且必须手动退出 .

.ps1文件应该运行程序并返回依赖于该程序输出的错误级别 . 但我很确定我还没有到达那里 .

我究竟做错了什么?

13 回答

  • 181

    如果您的脚本以 .ps1 扩展名命名并且您位于PowerShell窗口中,则只需运行 ./myscript.ps1 (假设该文件位于您的工作目录中) .

    无论如何,无论如何在Windows 10上使用PowerShell版本5.1都是如此,我认为我没有做任何事情来实现它 .

  • 8

    如果要在不修改默认脚本执行策略的情况下运行脚本,则可以在启动 Windows PowerShell 时使用旁路开关 .

    powershell [-noexit] -executionpolicy bypass -File <Filename>
    
  • 52

    如果你只有 PowerShell 1.0 ,这似乎就足够了:

    powershell -command - < c:\mypath\myscript.ps1
    

    它将脚本文件传递给PowerShell命令行 .

  • 150

    类型:

    powershell -executionpolicy bypass -File .\Test.ps1

    注意:这里 Test.ps1 是PowerShell脚本 .

  • 26

    满容易 . 右键单击Windows中的.ps1文件,然后在shell菜单中单击“使用PowerShell运行” .

  • 20

    我遇到了同样的问题,我尝试过并试过......最后我使用了:

    powershell.exe -noexit "& 'c:\Data\ScheduledScripts\ShutdownVM.ps1'"
    

    并将此行放在批处理文件中,这是有效的 .

  • 9

    一种简单的方法是使用PowerShell ISE,打开脚本,运行并调用脚本,函数......

    Enter image description here

  • 8
    • 启动Windows PowerShell,稍等片刻即可显示PS命令提示符

    • 导航到脚本所在的目录

    PS> cd C:\my_path\yada_yada\ (enter)
    
    • 执行脚本:
    PS> .\run_import_script.ps1 (enter)
    

    我错过了什么?

    或者:您可以从 cmd.exe 运行PowerShell脚本,如下所示:

    powershell -noexit "& ""C:\my_path\yada_yada\run_import_script.ps1""" (enter)
    

    据此blog post here

    或者您甚至可以从C#app运行Powershell脚本:-)

    Asynchronously execute PowerShell scripts from your C# application

  • 7

    如果您想使用Windows任务计划程序运行PowerShell脚本,请按照以下步骤操作:

    • 创建任务

    • Program/Script 设为 Powershell.exe

    • Arguments 设为 -File "C:\xxx.ps1"

    这是另一个答案,How do I execute a PowerShell script automatically using Windows task scheduler? .

  • 6

    在文件名前面使用 -File 参数 . 引号使PowerShell认为它是一串命令 .

  • 3

    如果您使用PowerShell 2.0,请使用PowerShell.exe的-File参数从其他环境(如cmd.exe)调用脚本,例如:

    Powershell.exe -File C:\my_path\yada_yada\run_import_script.ps1
    
  • 0
    • 给出脚本的路径,即cmd的路径设置:

    $> . c:\program file\prog.ps1

    • 运行PowerShell的入口点功能:

    例如, $> add or entry_func or main

  • 591

    使用cmd(BAT)文件:

    @echo off
    color 1F
    echo.
    
    C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -File "PrepareEnvironment.ps1"
    
    :EOF
    echo Waiting seconds
    timeout /t 10 /nobreak > NUL
    

    如果你需要 run as administrator

    • 创建指向命令提示符的快捷方式(我将其命名为Administrative Command Prompt)

    • 打开快捷方式的属性,然后转到“兼容性”选项卡

    • 在“权限级别”部分下,确保选中"Run this program as an administrator"旁边的复选框

相关问题