Last active
January 14, 2024 22:25
-
-
Save santisq/695822faa93a416ce46497fdeb46ee79 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
& { | |
[CmdletBinding()] | |
param() | |
$psi = [Diagnostics.ProcessStartInfo]@{ | |
UseShellExecute = $false | |
RedirectStandardError = $true | |
RedirectStandardOutput = $true | |
FileName = 'cmd.exe' | |
Arguments = '/c "ping -n 10 google.com & echo an error >&2"' | |
} | |
$proc = [Diagnostics.Process]@{ | |
StartInfo = $psi | |
} | |
$params = @{ | |
InputObject = $proc | |
EventName = 'OutputDataReceived' | |
SourceIdentifier = 'Process.Stdout' | |
Action = { | |
$cmdlet.WriteObject("$([char] 27)[32mSTDOUT:$([char] 27)[0m " + $EventArgs.Data) | |
} | |
} | |
$sub = Register-ObjectEvent @params | |
$sub.Module.SessionState.PSVariable.Set('cmdlet', $PSCmdlet) | |
$params['EventName'] = 'ErrorDataReceived' | |
$params['SourceIdentifier'] = 'Process.Stderr' | |
$params['Action'] = { | |
$cmdlet.WriteObject("$([char] 27)[91mSTDERR:$([char] 27)[0m " + $EventArgs.Data) | |
} | |
$sub = Register-ObjectEvent @params | |
$sub.Module.SessionState.PSVariable.Set('cmdlet', $PSCmdlet) | |
Register-ObjectEvent -InputObject $proc -EventName Exited -SourceIdentifier Process.Exited | |
try { | |
$proc.Start() | Out-Null | |
$proc.BeginOutputReadLine() | |
$proc.BeginErrorReadLine() | |
Wait-Event -SourceIdentifier Process.Exited | Remove-Event | |
} | |
finally { | |
Unregister-Event -SourceIdentifier Process.Stdout | |
Unregister-Event -SourceIdentifier Process.Stderr | |
Unregister-Event -SourceIdentifier Process.Exited | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment