I am running a batch file in a powershell script.
Powershell script(pw.ps1):
# Powershell script
$ScriptPath = "C:\Users\Administrator\Documents\bh.bat"
$out = cmd.exe /c "$ScriptPath" 2>&1 | Out-String
$flg = $?
echo "Output: $out"
if ($flg) {
echo "Worked"
} else {
echo "Failed"
}
Batch File(bh.bat):
REM Batch File
@echo on
Setlocal EnableDelayedExpansion
schtasks /query /tn T1
if %errorlevel% NEQ 1 (
echo "Task already scheduled"
) else (
echo "Task not scheduled"
)
exit /b 0
Output of powershell script:
PS C:\Users\Administrator\Documents> C:\Users\Administrator\Documents\pw.ps1
Output:
C:\Users\Administrator\Documents>REM Batch File
C:\Users\Administrator\Documents>Setlocal EnableDelayedExpansion
C:\Users\Administrator\Documents>schtasks /query /tn T1
cmd.exe : ERROR: The system cannot find the path specified.
At C:\Users\Administrator\Documents\pw.ps1:5 char:8
+ $out = cmd.exe /c "$ScriptPath" 2>&1 | Out-String
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (ERROR: The syst...path specified.:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
C:\Users\Administrator\Documents>if 1 NEQ 1 (echo "Task already scheduled" ) else (echo "Task not scheduled" )
"Task not scheduled"
C:\Users\Administrator\Documents>exit /b 0
Failed
PS C:\Users\Administrator\Documents>
My requirement is as follows:
- Powershell script should output "Failed" only if batch script fails with some errors such as syntax or runtime error.
- Powershell script should output "Worked" in two cases: task is found or not found. Currently Powershell script gives "Failed" as output if task is not found.
How can I check in the powershell script if the batch file ran successfully?