使用bat启动Powershell脚本

Dav*_*.ca 5 powershell

我有一个批处理文件test.bat来启动一个PowerShell脚本:

@pushd "C:\myscripts"
powershell .\test.ps1 arg1 "arg2 with space" arg3
@popd
Run Code Online (Sandbox Code Playgroud)

脚本test.ps1(位于C:\ myscripts)是一个非常简单的脚本:

# just print out the arguments
Write-Output ("args count: {0}" -f $args.length)
$args
Run Code Online (Sandbox Code Playgroud)

然后我尝试启动test.bat.我应该将三个参数传递给ps1,但我得到以下结果:

args count:5 arg1 arg2,空格arg3

我在脚本中的预期,args [0]应该是arg1和args [1]应该是"arg2 with space"而args3 [2]应该是arg3.我无法理解为什么脚本实际上得到5个参数.

如何将cmd或batch中的参数传递给powershell,就像我预期的那样?像这样:

args count: 3
arg1
arg2 with space
arg3
Run Code Online (Sandbox Code Playgroud)

Joe*_*oey 7

powershell .\test.ps1 arg1 'arg2 with space' arg3
Run Code Online (Sandbox Code Playgroud)

要么

powershell .\test.ps1 arg1 """arg2 with space""" arg3
Run Code Online (Sandbox Code Playgroud)

我认为你应该尽量避免使用双引号,因为cmd也已经使用过它们,因此有点难以预测PowerShell会得到什么.请记住,这会通过两个 shell 传递,因此会有两层转义/引用.

PowerShell本身并没有区分单引号和双引号.至少在这种情况下,差异是无关紧要的.