将带空格的字符串传递给参数 - powershell

时间:2016-05-03 09:06:35

标签: powershell

将带有空格的参数传递给powershell脚本时遇到问题。它似乎只适用于空格

之前的参数字符串的第一部分
[CmdletBinding()]
Param(

 [Parameter(Mandatory=$True, ParameterSetName='firewallCommand',Position=0,HelpMessage="Input Firewall Index")]
 [string]$fwName,

 [Parameter(Mandatory=$True, ParameterSetName='firewallCommand',Position=1,  HelpMessage="Input Firewall Command")]
 [string]$fwCommand)

在脚本中,这会将参数传递给以下命令:

 cprid_util -server $firewallIpAdd -verbose rexec -rcmd  "$fwCommand"

在命令行中,如果我运行它,它可以工作:

.\fwcommand_run.ps1 -fwName firewall-name -fwCommand "ps"

如果我运行它,它根本不起作用:

 .\fwcommand_run.ps1 -fwName firewall-name -fwCommand "ps -ef"

但如果我直接调用命令它确实有效:

cprid_util -server 10.1.128.4  -verbose rexec -rcmd  ps -ef

2 个答案:

答案 0 :(得分:2)

$fwCommand被注册为单个值。来自Powershell Community Extensions的Echoargs对于这样的情况非常有用:

$fwCommand = "ps -ef"
$firewallIpAdd = "127.0.0.1"

$command = "cprid_util -server $firewallIpAdd -verbose rexec -rcmd '$fwCommand'"
[management.automation.psparser]::Tokenize($command,[ref]$null) | Format-Table Content, Type -AutoSize

Content                Type
-------                ----
cprid_util          Command
-server    CommandParameter
127.0.0.1   CommandArgument
-verbose   CommandParameter
rexec       CommandArgument
-rcmd      CommandParameter
ps -ef               String

.\EchoArgs.exe -server $firewallIpAdd -verbose rexec -rcmd $fwCommand

Arg 0 is <-server>
Arg 1 is <127.0.0.1>
Arg 2 is <-verbose>
Arg 3 is <rexec>
Arg 4 is <-rcmd>
Arg 5 is <ps -ef>

您可以在空格上拆分值或使用Invoke-Expression

$firewallIpAdd = "127.0.0.1"
$fwCommand = "ps -ef"
Invoke-Expression ".\EchoArgs.exe -server $firewallIpAdd -verbose rexec -rcmd $fwCommand"

Arg 0 is <-server>
Arg 1 is <127.0.0.1>
Arg 2 is <-verbose>
Arg 3 is <rexec>
Arg 4 is <-rcmd>
Arg 5 is <ps>
Arg 6 is <-ef>

答案 1 :(得分:0)

我设法通过拆分$ fwCommand字符串

来实现这一点
 $commandSplit = $fwCommand -split ' '
 cprid_util -server $firewallIpAdd -verbose rexec -rcmd  $commandSplit[0] $commandSplit[1]}