Safest way to run BAT file from Powershell script

前端 未结 5 1764
眼角桃花
眼角桃花 2020-12-07 12:58

I can not get a powershell script to execute a bat file directly. For example, this works on the command line:

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

When

相关标签:
5条回答
  • 2020-12-07 13:22
    cmd.exe /c '\my-app\my-file.bat'
    
    0 讨论(0)
  • 2020-12-07 13:27

    Try this, your dot source was a little off. Edit, adding lastexitcode bits for OP.

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

    add -WindowStyle Hidden for invisible batch.

    0 讨论(0)
  • 2020-12-07 13:29

    Assuming my-app is a subdirectory under the current directory. The $LASTEXITCODE should be there from the last command:

    .\my-app\my-fle.bat
    

    If it was from a fileshare:

    \\server\my-file.bat
    
    0 讨论(0)
  • 2020-12-07 13:30

    To run the .bat, and have access to the last exit code, run it as:

     & .\my-app\my-fle.bat
    
    0 讨论(0)
  • 2020-12-07 13:39

    @Rynant 's solution worked for me. I had a couple of additional requirements though:

    1. Don't PAUSE if encountered in bat file
    2. Optionally, append bat file output to log file

    Here's what I got working (finally):

    [PS script code]

    & 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 讨论(0)
提交回复
热议问题