使用带有equals和period的single-hypen参数执行外部命令

The*_*Sky 6 powershell powershell-2.0

我有一个接受这样的参数的工具(例如in test.ps1):

foo.exe -name="john"
Run Code Online (Sandbox Code Playgroud)

因此,每个参数都使用单个连字符-,名称,等于=,然后是参数的值来指定.

当我从PowerShell调用这个确切的表达式时,它会毫无问题地执行.但是,当其中一个值包含这样的句点时.:

foo.exe -name="john.doe"
Run Code Online (Sandbox Code Playgroud)

运行它会导致语法错误:

$ ./test.ps1字符串开始:在test.ps1:1 char:24 + foo.exe -name ="john.doe <<<<"缺少终结符:".在test.ps1:1 char: 25
+ foo.exe -name ="john.doe"<<<<
+ CategoryInfo:ParserError:(:String)[],ParseException
+ FullyQualifiedErrorId:TerminatorExpectedAtEndOfString

我可以阻止PowerShell解释这一点的一些方法是:

  • foo.exe "-name=`"john.doe`""
  • foo.exe '-name="john.doe"'
  • PowerShell V3 +: foo.exe --% -name="john.doe"
  • $nameArg = "john.doe"; foo.exe -name="$nameArg"

但是,其中一些选项会阻止变量插值.还有其他方法可以阻止PowerShell导致语法问题吗?在这个特定的实例中(添加句点),为什么PowerShell有解释这个问题?

The*_*ian 0

我以前遇到过这个问题,我不知道这是否是解决这个问题的最佳方法,但我以前做过的一种方法是构建要执行的命令字符串,然后使用Invoke-Expression.

$MyCommand = '& foo.exe --% -name="{0}"' -f 'john.doe'
Invoke-Expression $MyCommand
Run Code Online (Sandbox Code Playgroud)

或者,更具体地说,对于我的问题,我有几个参数会改变我在哈希表中的参数,所以我会将它们添加到命令中。根据您的命令,我可能有:

$MyArgs = @{
    name = 'john.doe'
    request = 'delete file'
    argument = '\jdoe\temp\nsfwstash.zip'
}
$MyCommand = '& foo.exe --%'
$MyArgs.Keys | ForEach{
    $MyCommand = $MyCommand + (' {0}="{1}"' -f $_, $MyArgs[$_])
}
Invoke-Expression $MyCommand
Run Code Online (Sandbox Code Playgroud)

这最终会调用一个命令:

& foo.exe --% -name="john.doe" -request="delete file" -argument="\jdoe\temp\nsfwstash.zip"
Run Code Online (Sandbox Code Playgroud)