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

我无法使用 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"

注意: 它必须返回最后的 exitcode,因为我需要验证批处理的成功。

342214 次浏览

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.

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

 & .\my-app\my-fle.bat
cmd.exe /c '\my-app\my-file.bat'

@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

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

What about invoke-item script.bat.

You can simply do:

Start-Process -FilePath "C:\PathToBatFile\FileToExecute.bat" -ArgumentList $argstr -Wait -NoNewWindow

Here,

ArgumentList - to pass parameters or parameter values if needed by bat file

Wait - waits for the process(bat) to complete

NoNewWindow - starts the new process in the current console window.

Even using win_shell ansible module this can be achieved:

- name: Install the WebApp Service
win_shell: 'Service_Install.bat'
args:
executable: cmd
chdir: 'D:\MyWebApp\Services'
register: result

Here D:\MyWebApp\Services is the location where your .bat file is available.