Skip to content

Instantly share code, notes, and snippets.

@mintsoft
Last active May 24, 2023 17:50
Show Gist options
  • Select an option

  • Save mintsoft/6502081 to your computer and use it in GitHub Desktop.

Select an option

Save mintsoft/6502081 to your computer and use it in GitHub Desktop.
Powershell to run a bunch of commands in new processes, wait until they're all done and output all the stdout/stderr. If one of the commands returns non-0 exit code then entire script returns 1
#To add more commands, hack them into the $commands array:
$commands = @(
@{"cmd" = "D:\Documents\Powershell\battwo.bat"; "args" = "yo"},
@{"cmd" = "D:\Documents\Powershell\batone.bat"; "args" = "yo2"}
);
$jobs = @();
foreach($cmd in $commands) {
$startinfo = new-object System.Diagnostics.ProcessStartInfo
$startinfo.FileName = $cmd.cmd;
$startinfo.Arguments = $cmd.args;
$startinfo.WindowStyle = "Hidden";
$startinfo.CreateNoWindow = $True;
$startinfo.RedirectStandardError = $True;
$startinfo.RedirectStandardOutput = $True;
$startinfo.UseShellExecute = $False;
$jobs += @{
"process" = [System.Diagnostics.Process]::Start($startinfo);
"startInfo" = $startinfo;
};
}
$hasError=$false
foreach($job in $jobs) {
Write-Host "================ Process ===================="
Write-Host $job.process.Id ":" $job.process.startInfo.FileName $job.process.startInfo.Arguments
Write-Host "================= Output ===================="
$job.process.StandardOutput.ReadToEnd()
$stderr = $job.process.StandardError.ReadToEnd()
if($stderr) {
[Console]::Error.Write($error)
}
if($job.process.ExitCode -ne 0) {
$hasError=$true
}
Write-Host "=================== End ====================="
}
if($hasError){
#Write-Error "OMG, there has been an error! please check the above output";
[Console]::Error.WriteLine("OMG, there has been an error! please check the above output")
exit 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment