如何将带空格的字符串传递到PowerShell?
鉴于: 这样使用:如何将带空格的字符串传递到PowerShell?,powershell,Powershell,鉴于: 这样使用: # test1.ps1 param( $x = "", $y = "" ) &echo $x $y 产出: powershell test.ps1 test.ps1 -x "Hello, World!" -y "my friend" 产出: powershell test.ps1 test.ps1 -x "Hello, World!" -y "my friend" 我希望看到: Hello, my 这是一个cmd.exe问题,但是有一些方
# test1.ps1
param(
$x = "",
$y = ""
)
&echo $x $y
产出:
powershell test.ps1
test.ps1 -x "Hello, World!" -y "my friend"
产出:
powershell test.ps1
test.ps1 -x "Hello, World!" -y "my friend"
我希望看到:
Hello,
my
这是一个
cmd.exe
问题,但是有一些方法可以解决它
Hello, World! my friend
-file
参数
powershell test.ps1 -x 'hello world' -y 'my friend'
.bat
包装
powershell -file test.ps1 -x "hello world" -y "my friend"
然后称之为:
@rem test.bat
@powershell -file test.ps1 %1 %2 %3 %4
我有一个类似的问题,但在我的例子中,我试图运行cmdlet,调用是在一个蛋糕脚本中进行的。在这种情况下,单引号和
-file
参数不起作用:
test.bat -x "hello world" -y "my friend"
结果错误:Get AuthenticodeSignature:找不到接受参数“with”的位置参数。
我希望尽可能避免使用批处理文件
解决方案
所做的工作是使用带有/S的cmd包装来展开外部引号:
powershell Get-AuthenticodeSignature 'filename with spaces.dll'
可以使用倒勾`来转义空格:
cmd /S /C "powershell Get-AuthenticodeSignature 'filename with spaces.dll'"
在我的例子中,一个可能的解决方案是嵌套单引号和双引号
PS & C:\Program` Files\\....
这在powershell提示符下对我有效,但在cmd.exe下失败。这使得它成为cmd.exe的限制。在那里使用单引号似乎是可行的。。。这很奇怪,因为我认为cmd.exe根本没有处理单引号。所以这是powershell问题还是cmd.exe问题?您似乎已经回答了自己的问题?我在Windows中从计划任务运行PowerShell脚本时遇到了这个问题。脚本的一个参数用于构建路径,其中有一个空间,脚本失败,因为它删除了空间后面的所有内容。添加
-File
参数修复了问题。-File-不起作用,我通过直接引用arg
%1`并转义引号解决了问题,该引号给出:\%1\
。然后,我可以毫无问题地使用$arg
(路径在第一个空格处不再中断),或者如上所述,在命令行中转义引号,例如powershell somefile \“arg with space\”,我正试图使用多个配置文件运行java应用程序,如profile1,profile2
您的解决方案是唯一适合我的解决方案。