如何使用路径中的变量运行bat文件

时间:2019-07-02 20:56:29

标签: powershell

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

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

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

是我想要的,但由于它是意外令牌而无法运行。

尝试过

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

我是PowerShell的新手。有我想念的转义键吗?

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

1 个答案:

答案 0 :(得分: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

相关问题