Safest way to run BAT file from Powershell script
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.
cmd.exe /c '\my-app\my-file.bat'
To run the .bat, and have access to the last exit code, run it as:
& .\my-app\my-fle.bat
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.
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
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.