从Powershell脚本运行BAT文件的最安全方法

问题描述 投票:71回答:5

我无法获得Powershell脚本来直接执行bat文件。例如,这在命令行上有效:

.\\my-app\my-fle.bat

当我将此命令添加到脚本时,它输出:

The term '.\\my-app\my-file.bat' is not recognized as the 
name of a cmdlet, function, script file, or operable program. 
Check the spelling of the name, or if a path was included, 
verify that the path is correct and try again.

我也尝试了以下操作,结果相同:

& .\\my-app\my-fle.bat
& ".\\my-app\my-fle.bat"
\my-app\my-fle.bat
& \my-app\my-fle.bat
& "\my-app\my-fle.bat"

注意:它必须返回lastexitcode,因为我需要验证批处理是否成功。

batch-file powershell
5个回答
90
投票
cmd.exe /c '\my-app\my-file.bat'

30
投票
要运行.bat,并有权访问最后一个退出代码,请以以下方式运行它:

& .\my-app\my-fle.bat


25
投票
尝试一下,您的点源稍微有些偏离。编辑,为OP添加lastexitcode位。

$A = Start-Process -FilePath .\my-app\my-fle.bat -Wait -passthru;$a.ExitCode

为不可见的批处理添加-WindowStyle Hidden

0
投票
@@ Rantant的解决方案为我工作。不过,我还有一些其他要求:

    如果在bat文件中遇到,请不要暂停
  1. 可选,将bat文件输出附加到日志文件中
  • 这是我最后要从事的工作:

    [[PS脚本代码]

    & runner.bat bat_to_run.bat logfile.txt

    [runner.bat]

    @echo OFF REM This script can be executed from within a powershell script so that the bat file REM passed as %1 will not cause execution to halt if PAUSE is encountered. REM If {logfile} is included, bat file output will be appended to logfile. REM REM Usage: REM runner.bat [path of bat script to execute] {logfile} if not [%2] == [] GOTO APPEND_OUTPUT @echo | call %1 GOTO EXIT :APPEND_OUTPUT @echo | call %1 1> %2 2>&1 :EXIT


  • 0
    投票
    假设my-app是当前目录下的子目录。 $ LASTEXITCODE应该位于最后一条命令中:

    .\my-app\my-fle.bat

    © www.soinside.com 2019 - 2024. All rights reserved.