如何将带空格的字符串传入 PowerShell?
How do I pass in a string with spaces into PowerShell?
鉴于:
# test1.ps1
param(
$x = "",
$y = ""
)
&echo $x $y
这样使用:
powershell test.ps1
输出:
> <blank line>
但是接下来就出错了:
test.ps1 -x "Hello, World!" -y "my friend"
输出:
Hello,
my
我期待看到:
Hello, World! my friend
好吧,这是一个 cmd.exe
问题,但有一些方法可以解决它。
使用单引号
powershell test.ps1 -x 'hello world' -y 'my friend'
使用-file
参数
powershell -file test.ps1 -x "hello world" -y "my friend"
使用以下内容创建一个 .bat
包装器
@rem test.bat
@powershell -file test.ps1 %1 %2 %3 %4
然后调用它:
test.bat -x "hello world" -y "my friend"
我有一个类似的问题,但在我的例子中,我试图 运行 一个 cmdlet,并且调用是在 Cake 脚本中进行的。在这种情况下,单引号和 -file
参数不起作用:
powershell Get-AuthenticodeSignature 'filename with spaces.dll'
产生的错误:Get-AuthenticodeSignature : A positional parameter cannot be found that accepts argument 'with'.
我想尽可能避免使用批处理文件。
解决方案
有用的是使用带有 /S 的 cmd 包装器来打开外部引号:
cmd /S /C "powershell Get-AuthenticodeSignature 'filename with spaces.dll'"
可以使用反引号 ` 来转义空格:
PS & C:\Program` Files\....
在我的例子中,一个可能的解决方案是嵌套单引号和双引号。
test.ps1 -x '"Hello, World!"' -y '"my friend"'
鉴于:
# test1.ps1
param(
$x = "",
$y = ""
)
&echo $x $y
这样使用:
powershell test.ps1
输出:
> <blank line>
但是接下来就出错了:
test.ps1 -x "Hello, World!" -y "my friend"
输出:
Hello,
my
我期待看到:
Hello, World! my friend
好吧,这是一个 cmd.exe
问题,但有一些方法可以解决它。
使用单引号
powershell test.ps1 -x 'hello world' -y 'my friend'
使用
-file
参数powershell -file test.ps1 -x "hello world" -y "my friend"
使用以下内容创建一个
.bat
包装器@rem test.bat @powershell -file test.ps1 %1 %2 %3 %4
然后调用它:
test.bat -x "hello world" -y "my friend"
我有一个类似的问题,但在我的例子中,我试图 运行 一个 cmdlet,并且调用是在 Cake 脚本中进行的。在这种情况下,单引号和 -file
参数不起作用:
powershell Get-AuthenticodeSignature 'filename with spaces.dll'
产生的错误:Get-AuthenticodeSignature : A positional parameter cannot be found that accepts argument 'with'.
我想尽可能避免使用批处理文件。
解决方案
有用的是使用带有 /S 的 cmd 包装器来打开外部引号:
cmd /S /C "powershell Get-AuthenticodeSignature 'filename with spaces.dll'"
可以使用反引号 ` 来转义空格:
PS & C:\Program` Files\....
在我的例子中,一个可能的解决方案是嵌套单引号和双引号。
test.ps1 -x '"Hello, World!"' -y '"my friend"'