[我一直在努力弄清楚为什么Powershell忽略了命令行参数,而我认为我终于发现以某种方式在字符串参数上加上反斜杠会使参数解析变得混乱。
我有
param (
[Parameter(Mandatory=$true)][String]$p1,
[Parameter(Mandatory=$true)][String]$p2
)
Write-Output "p1:$p1, p2:$p2"
最终,我需要从Windows任务计划程序中调用类似的内容,这意味着使用powershell.exe
作为程序并将此脚本和参数添加为args。
在生产中,p1是文件路径。所以我尝试:
PS C:\source> C:\Windows\System32\windowspowershell\v1.0\powershell.exe -ExecutionPolicy Bypass -File .\myScript.ps1 -p1 'C:\Program Files\' -p2 asdf
cmdlet myScript.ps1 at command pipeline position 1
Supply values for the following parameters:
p2:
为什么提示?参数就在那里。我最终偶然发现删除了p1的结尾反斜杠:
PS C:\source> C:\Windows\System32\windowspowershell\v1.0\powershell.exe -ExecutionPolicy Bypass -File .\myScript.ps1 -p1 'C:\Program Files' -p2 asdf
p1:C:\Program Files, p2:asdf
这是错误吗?
C:\Windows\System32\windowspowershell\v1.0\powershell.exe -ExecutionPolicy Bypass -file .\myScript.ps1 -p1 "C:\Program Files\\" -p2 asdf
p1:C:\Program Files\, p2:asdf