[英]powershell sending multiple parameter to a external command
我试图从powershell脚本运行外部exe。
这个exe需要4个参数。
我一直在尝试invoke-item,invoke-command和'C:\\ program files \\ mycmd.exe myparam'的每一个组合,在C:\\中创建一个快捷方式来摆脱路径中的空格。
我可以使用一个参数,但不能更多。 我收到各种错误。
总结一下,如何向exe发送4个参数?
如果用手写的话最好。 一旦你看到发生了什么,你可以通过在每个参数之间使用逗号来缩短它。
$arg1 = "filename1"
$arg2 = "-someswitch"
$arg3 = "C:\documents and settings\user\desktop\some other file.txt"
$arg4 = "-yetanotherswitch"
$allArgs = @($arg1, $arg2, $arg3, $arg4)
& "C:\Program Files\someapp\somecmd.exe" $allArgs
......速记:
& "C:\Program Files\someapp\somecmd.exe" "filename1", "-someswitch", "C:\documents and settings\user\desktop\some other file.txt", "-yetanotherswitch"
在简单的情况下,将参数传递给本机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"
这不起作用,我们可以使用名为echoargs.exe
的PowerShell社区扩展 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>
请注意,使用PowerShell解释和评估Arg3 $(user)
并生成空字符串。 您可以使用单引号而不是double qoutes来解决此问题和大量类似问题,除非您确实需要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>
如果所有其他方法都失败了,请使用here字符串和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。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.