在简单的情况下,将参数传递给本机 exe 就像使用内置命令一样简单:
PS> ipconfig /allcompartments /all
当您指定 EXE 的完整路径并且该路径包含空格时,您可能会遇到问题。例如,如果 PowerShell 看到这个:
PS> C:\Program Files\Microsoft SDKs\Windows\v7.0\Bin\sn.exe -k .\pubpriv.snk
它将命令解释为“C:\Program”和“Files\Microsoft”作为第一个参数,“SDKs\Windows\v7.0\Bin\sn.exe”作为第二个参数,依此类推。解决方案是将路径放在字符串中,使用调用运算符& 调用路径命名的命令 例如:
PS> & 'C:\Program Files\Microsoft SDKs\Windows\v7.0\Bin\sn.exe' -k .\pubpriv.snk
我们遇到的下一个问题是当参数很复杂和/或使用 PowerShell 专门解释的字符时,例如:
PS> sqlcmd -v user="John Doe" -Q "select '$(user)' as UserName"
这不起作用,我们可以使用 PowerShell Community Extensions 中的一个名为 echoargs.exe 的工具来调试它,它可以准确地向您展示本机 EXE 如何从 PowerShell 接收参数。
PS> echoargs -v user="John Doe" -Q "select '$(user)' as UserName"
The term 'user' is not recognized as the name of a cmdlet, function,
script file, or operable program. Check the spelling of the name, ...
<snip>
Arg 0 is <-v>
Arg 1 is <user=John Doe>
Arg 2 is <-Q>
Arg 3 is <select '' as UserName>
请注意,使用 Arg3 $(user) 由 PowerShell 解释和评估,并产生一个空字符串。您可以通过使用单引号而不是双引号来解决此问题和大量类似问题,除非您确实需要 PowerShell 来评估变量,例如:
PS> echoargs -v user="John Doe" -Q 'select "$(user)" as UserName'
Arg 0 is <-v>
Arg 1 is <user=John Doe>
Arg 2 is <-Q>
Arg 3 is <select $(user) as UserName>
如果所有其他方法都失败,请使用此处的字符串和 Start-Process,如下所示:
PS> Start-Process echoargs -Arg @'
>> -v user="John Doe" -Q "select '$(user)' as UserName"
>> '@ -Wait -NoNewWindow
>>
Arg 0 is <-v>
Arg 1 is <user=John Doe>
Arg 2 is <-Q>
Arg 3 is <select '$(user)' as UserName>
请注意,如果您使用的是 PSCX 1.2,则需要像这样为 Start-Process 添加前缀 - Microsoft.PowerShell.Management\Start-Process 以使用 PowerShell 的内置 Start-Process cmdlet。