使用批处理启动Powershell脚本

5

我有一个批处理文件test.bat,用于启动powershell脚本:

@pushd "C:\myscripts"
powershell .\test.ps1 arg1 "arg2 with space" arg3
@popd

脚本test.ps1(位于C:\ myscripts)非常简单,如下所示:

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

接着我尝试启动test.bat。我应该传递三个参数到ps1文件,但是我得到了以下结果:

参数数量:5 arg1 arg2 with space arg3

在脚本中,我期望args[0]是arg1,args[1]是"arg2 with space",args[2]是arg3。我不明白为什么脚本实际上会得到5个参数。

我该如何将参数从cmd或批处理文件传递到powershell中,以达到我期望的效果?就像这样:

args count: 3
arg1
arg2 with space
arg3
2个回答

7
powershell .\test.ps1 arg1 'arg2 with space' arg3

或者

powershell .\test.ps1 arg1 """arg2 with space""" arg3

我认为你应该尽量避免使用双引号,因为cmd已经使用了它们,因此很难预测PowerShell会得到什么。请记住,这将通过两个 shell传递,因此需要进行两层转义/引用。

PowerShell本身在单引号和双引号之间没有太大区别。至少在这种情况下,差异是无关紧要的。


0

好的,我想我明白了:

@pushd "C:\myscripts"
powershell .\test.ps1 arg1 'arg2 with space' arg3
@popd

使用单引号代替双引号。也许在 PS 中它们的含义不同。


1
他们并不一样。但是对于 cmd,它们确实有不同的含义。 - Joey

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接