test.ps1 包含:
echo ok
我在命令提示符 (cmd.exe) 中有一行需要调用 powershell.exe,同时传递“-File”选项和“-Command”选项。
使用这种错误的语法:
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 Pro 64 位
Powershell 版本:5.1.19041.1237(集成在 Windows 10 中)。