【问题标题】:Use bat to start Powershell script使用bat启动Powershell脚本
【发布时间】:2010-12-20 18:10:38
【问题描述】:

我有一个批处理文件 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 参数1 arg2 和 空间 arg3

我在脚本中所期望的,args[0] 应该是 arg1,args[1] 应该是“arg2 with space”,而 args3[2] 应该是 arg3。我不明白为什么脚本实际上有 5 个参数。

如何按预期将参数从 cmd 或批处理传递到 powershell?像这样:

args count: 3
arg1
arg2 with space
arg3

【问题讨论】:

    标签: powershell


    【解决方案1】:
    powershell .\test.ps1 arg1 'arg2 with space' arg3
    

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

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

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

    【讨论】:

      【解决方案2】:

      好的。我想我明白了:

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

      单引号字符而不是双引号。也许它们在 PS 中的含义不同。

      【讨论】:

      • 他们没有。但是对于cmd,它们确实意味着不同的东西。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-01
      • 2019-06-16
      • 1970-01-01
      • 2011-09-19
      • 2012-11-04
      • 2017-02-02
      • 1970-01-01
      相关资源
      最近更新 更多