2017-08-31 19 views
3

我正在编写一个脚本,该脚本使用给定的命令行参数远程启动程序。出于某种原因,我的一个字符串中的逗号(格式为--Tags Small,Medium,Large)会在Invoke-Command和应用程序读取参数之间的某个时间内对空格进行更改。Invoke-Command看起来将我的逗号转换为空格

PowerShell的:

param(
[string]$N = "remoteHost", 
[string]$U = "user", 
[string]$P = "pass", 
[string]$App = "App.exe", 
[string]$Arg = "--Tags Small,Medium,Large" 
) 
Write-Host "Connecting to" $N "..." 
$sec = ConvertTo-secureString $P -asPlainText -Force 
$session=New-PSSession -ComputerName $N -Credential (New-Object System.Management.Automation.PSCredential ($U,$sec)) 
$cmd = $App + " " + $Arg 
Write-Host $cmd 
$sb = ([scriptblock]::Create($cmd)) 
Write-Host $cmd 
Invoke-Command -Session $session -ScriptBlock $sb 
Write-Host "Disconnecting..." 
Remove-PSSession -Session $session 

两个$ CMD和$ SB写主机的显示我的期望:

"App.exe --Tags Small,Medium,Large" 

但在 “APP.EXE” 应用程序,它接收ARGS:

"--Tags Small Medium Large" 

如果我通过命令行使用完全相同的字符串运行App.exe,它会看到逗号,因为我认为c颠覆正在发生在PowerShell中。

在应用程序和最后一个写主机之间唯一的事情就是Invoke-Command,所以我在想它以某种方式将逗号转换为空格。我的问题是:

  1. 为什么要转换逗号?
  2. 解决这个问题的最佳方法是什么?

回答

2

:你将一个命令字符串

"App.exe --Tags Small,Medium,Large" 

到脚本块。结果是一样的,如果你想创建的脚本块这样的:

$sb = {App.exe --Tags Small,Medium,Large} 

当调用脚本块解析器解释Small,Medium,Large作为一个字符串数组。但是,因为你正在运行一个外部命令,你的命令行会被转换为一个字符串的某个字符串(因为在这一天结束的时候这就是CreateProcess的期望)。重整字符串数组转换为字符串串接与output field separator$OFS,缺省是空格)数组元素,所以数组变为Small Medium Large和你的命令行最终被

App.exe --Tags Small Medium Large 

为了避免这种情况加上引号的说法,所以它是作为一个逗号分隔的字符串传递:当我打电话写主机$ SB

[string]$Arg = "--Tags 'Small,Medium,Large'" 
+0

所以,我看到的是不是实际上有逗号,那只是形式如何PowerShell的scriptblocks?令人沮丧的巧合。我测试了这个修复程序,它运行了 –

+0

逗号在那里。但是当你调用scriptblock并且命令被实际解析时它们会被移除。如果您只需在PowerShell控制台中输入“App.exe - 标记小,中,大”,您应该会看到相同的行为。 –

0

powershell解析器正在将“Small,Medium,Large”解释为一个数组,并将它们展开为3个单独的参数。你将不得不做一些报价说服PowerShell将它们解释为一个字符串,并把它们作为一个单独的参数:

$Arg = "--Tags '""Small,Medium,Large""'" 
相关问题