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 I add this command to a script, it outputs:

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. 

I also tried the following, with the same result:

& .\\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" 

Note: It must return the lastexitcode as I need to verify success of batch.

2

7 Answers

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

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

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

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.

2

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.

1

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 

@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 

What about invoke-item script.bat.

0

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy