使用 bat 启动 Powershell 脚本 [英] Use bat to start Powershell script
问题描述
我有一个批处理文件 test.bat 来启动 powershell 脚本:
I have a batch file test.bat to start a powershell script:
@pushd "C:\myscripts"
powershell .\test.ps1 arg1 "arg2 with space" arg3
@popd
脚本 test.ps1(位于 C:\myscripts)非常简单,例如:
The script test.ps1 (located at C:\myscripts) is a very simple one like:
# just print out the arguments
Write-Output ("args count: {0}" -f $args.length)
$args
然后我尝试启动 test.bat.我应该将三个参数传递给 ps1,但得到以下结果:
Then I tried to start test.bat. I should get three arguments passed to ps1 but I got the following result:
参数数:5arg1arg2和空间arg3
args count: 5 arg1 arg2 with space arg3
我在脚本中所期望的,args[0] 应该是 arg1,args[1] 应该是arg2 with space",args3[2] 应该是 arg3.我不明白为什么脚本实际上有 5 个参数.
What I expected in the script, args[0] should arg1 and args[1] should be "arg2 with space" and args3[2] be arg3. I cannot understand why the script actually gets 5 arguments.
如何按照我的预期将参数从 cmd 或 batch 传递到 powershell?像这样:
How can I pass parameters from cmd or batch to powershell as what I expected? Like this:
args count: 3
arg1
arg2 with space
arg3
推荐答案
powershell .\test.ps1 arg1 'arg2 with space' arg3
或
powershell .\test.ps1 arg1 """arg2 with space""" arg3
我认为您应该尽量避免使用双引号,因为 cmd 也已经使用了它们,因此很难预测 PowerShell 会得到什么.请记住,这会通过两个 shell,因此需要两层转义/引用.
I think you should try to avoid using double quotes as cmd already uses them too and therefore it's a little hard to predict what exactly PowerShell will get. Remember that this gets passed through two shells and therefore two layers of escaping/quoting.
PowerShell 本身对单引号和双引号没有太大区别.至少在这种情况下,差异是无关紧要的.
PowerShell itself doesn't make much of a distinction between single and double quotes. At least in this context the difference is irrelevant.
这篇关于使用 bat 启动 Powershell 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!