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

时间:2013-12-17 21:45:22

标签: batch-file powershell

我无法获得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,因为我需要验证批处理是否成功。

6 个答案:

答案 0 :(得分:76)

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

答案 1 :(得分:27)

要运行.bat,并且可以访问最后一个退出代码,请将其运行为:

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

答案 2 :(得分:23)

试试这个,你的点源有点偏。编辑,为OP添加lastexitcode位。

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

为隐身批次添加-WindowStyle Hidden

答案 3 :(得分:2)

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

.\my-app\my-fle.bat

如果来自文件共享:

\\server\my-file.bat

答案 4 :(得分:0)

@Rynant的解决方案对我有用。不过,我还有一些其他要求:

  1. 如果在bat文件中遇到,请不要暂停
  2. (可选)将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

答案 5 :(得分:0)

invoke-item script.bat 怎么样。