【发布时间】:2021-12-22 07:34:43
【问题描述】:
test.ps1 包含:
echo ok
我在命令提示符 (cmd.exe) 中有一行需要通过“-File”选项和“-Command”选项调用 powershell.exe。
使用这种错误的语法:
powershell.exe -File "test.ps1" -Command "echo test"
“-Command”和“echo test”作为参数传递给“test.ps1”脚本文件。实际上输出是:
ok
我希望作为输出:
ok
test
另一方面,如果我反转“-Command”和“-File”选项:
powershell.exe -Command "echo test" -File "test.ps1"
“-File”和“test.ps1”是“-Command”选项参数的简单延续。实际上输出是:
test
-File
test.ps1
我希望作为输出:
test
ok
“-Command”选项的帮助:
"如果 Command 的值是字符串,它必须是命令中的最后一个参数,在命令之后键入的任何字符都被解释为命令参数。"。
这是一个严重错误的声明,因此应向 Microsoft 报告错误。
问题:
也就是说,写命令的正确方法是什么?
回答要求:
作为一种解决方案,我想要一个不使用“-Command”选项参数调用文件的方法;所以,即使它有效,我也不想要这样的东西:
powershell.exe -Command "echo test; & \".\test.ps1\""
此命令最终需要用作注册表项(经典子项“Shell\Open\Command”)中的值。
例如目录[HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell\Open\Command]:
这行得通:
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -Command "if((Get-ExecutionPolicy ) -ne 'AllSigned') { Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process -Force }; & \"%1\""
这不是:
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -Command "if((Get-ExecutionPolicy ) -ne 'AllSigned') { Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process -Force }" -File "%1"
因为在命令之后键入的任何字符都被解释为命令参数。
Windows 10 专业版 64 位
Powershell 版本:5.1.19041.1237(集成在 Windows 10 中)。
【问题讨论】:
-
你能用
powershell.exe -File "test.ps1" -Command "& {echo test}"试试吗 -
这个有实际需要吗?
powershell echo test; .\test.ps1或者相反呢? -
此命令最终需要用作注册表项(经典子项“Shell\command”)中的值。
-
@MarioPalumbo 你能举个例子吗?
-
这有效:
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -Command "if((Get-ExecutionPolicy ) -ne 'AllSigned') { Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process -Force }; & \"%1\""这不是:"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -Command "if((Get-ExecutionPolicy ) -ne 'AllSigned') { Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process -Force }" -File "%1",因为在命令之后键入的任何字符都被解释为命令参数。