【问题标题】:How to run a bat file with variable in path如何在路径中运行带有变量的bat文件
【发布时间】:2019-07-02 20:56:29
【问题描述】:

我正在尝试制作一个审计脚本,而我现有的一些脚本是 .bat 文件,我想从 powershell 运行并检查输出是否成功/失败。

我尝试过使用 start-process,但无法正确捕获输出。我看到输出的方式是通过将 .bat 分配给一个变量来运行它。但是,我的路径以可变驱动器号开头(因为它是通过 USB 运行的。

$batExample = $USB\Audit\Script\Agent.bat

是我想要的,但它不会运行,因为它是一个意外的令牌。

试过

$batExample = "$USB\Audit\Script\Agent.bat"
and 
$batExample = "$USB"\Audit\Script\Agent.bat

我是 powershell 新手。是否有我缺少的转义键?

我确定这是一个小的语法问题,但我已经尝试了所有我能想到的步骤。谢谢!

【问题讨论】:

  • 最后两个看起来都可以正常工作。 [皱眉]您可能想要使用Join-Path cmdlet 来构建您的路径。它也更安全,因为它可以理解路径分隔符。
  • 你能解释一下@Lee_Dailey。我正在研究它,但我不太明白为什么它更安全。我敢肯定,但有什么区别?
  • *-Path 命令知道路径分隔符之类的东西,因此可以防止您意外遗漏一个...或添加太多。另外,您不必摆弄单/双引号的东西。 [咧嘴]

标签: powershell


【解决方案1】:

要调用批处理文件,您需要在路径前加上&。将输出通过管道传输到 Out-String 以将其捕获为变量。

PS C:\_scripts> "@ECHO This is the sample output line 1`n@ECHO This is the sample output line 2" | Out-File test.bat -Encoding ascii
PS C:\_scripts> $testoutput = & ".\test.bat" | Out-String
PS C:\_scripts> $testoutput
This is the sample output line 1
This is the sample output line 2

这应该适用于您的示例:

$batExample = & "$USB\Audit\Script\Agent.bat" | Out-String

如果您需要批处理文件中的ERRORLEVEL,您可以使用$LASTEXITCODE automatic variable

【讨论】:

  • 谢谢,这正是我所需要的。
猜你喜欢
  • 2015-07-26
  • 2014-10-12
  • 1970-01-01
  • 1970-01-01
  • 2020-12-12
  • 2014-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多