【问题标题】:Calling a Powershell script with the "-command" parameter instead of "-file"使用“-command”参数而不是“-file”调用 Powershell 脚本
【发布时间】:2015-05-21 21:51:27
【问题描述】:

这样调用powershell脚本有什么区别:

powershell.exe -file "myfile.ps1"

像这样(也可以):

powershell.exe -command "myfile.ps1"

谢谢,罗伯特

【问题讨论】:

  • 你看powershell.exe -?帮助了吗?它解释了主要区别。如果您对细微的差异感兴趣,那么问题中并不清楚。
  • 当然我查看了帮助。我很惊讶“-command”甚至可以按照我上面写的方式工作,因为它没有记录。问题是,脚本的执行方式有什么不同。例如,在第二种情况下,终止错误似乎无法按预期工作。但我不确定。我不能问更详细,因为我不知道更多细节。 :)

标签: powershell command-line command-line-arguments


【解决方案1】:

运行powershell.exe -File 将返回脚本设置的退出代码,而运行powershell.exe -Command 将在脚本以非零退出代码终止时返回1,否则返回0。

C:\>type "C:\path\to\test.ps1"
exit 5

C:\>powershell.exe -command "C:\path\to\test.ps1"

C:\>echo %errorlevel%
1

C:\>powershell.exe -file "C:\path\to\test.ps1"

C:\>echo %errorlevel%
5

【讨论】:

  • 将此添加到PowerShellTraps 作为Exit-code-5-with-File-1-with-Command
【解决方案2】:

powershell.exe -file "myfile.ps1" — 表示:启动 PowerShell 并在全局范围内执行文件 myfile.ps1(文件名被认为与当前目录相关)。
powershell.exe -command "myfile.ps1" — 表示:启动 PowerShell 并执行命令 @987654324 @,PowerShell 允许您通过在命令行中输入脚本文件的名称来执行脚本文件。

区别:

  1. 如果没有点源运算符 . myfile.ps1 PowerShell 在命令解析为脚本文件时创建新范围。
  2. PowerShell 不在当前目录中查找命令源。因此,如果文件myfile.ps1 驻留在当前目录中,而当前目录不在PATH 环境变量中,则PowerShell 找不到myfile.ps1 命令。
  3. 如果文件myfile.ps1可以在当前目录之前的PATH环境变量中提到的任何目录中找到,则myfile.ps1命令将被解析为该文件而不是当前目录中的文件myfile.ps1
  4. 您可以在您的配置文件中创建别名,例如 New-Alias myfile.ps1 DoSomethingElse,在这种情况下,myfile.ps1 命令将被视为对该别名的引用,而不是对 myfile.ps1 文件的引用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-02
    • 1970-01-01
    • 1970-01-01
    • 2019-03-24
    • 2020-12-04
    • 1970-01-01
    相关资源
    最近更新 更多