Skip to content

Instantly share code, notes, and snippets.

@santisq
Created May 20, 2022 23:16
Show Gist options
  • Select an option

  • Save santisq/c7f4a442c41abe81e869877c0f999ee0 to your computer and use it in GitHub Desktop.

Select an option

Save santisq/c7f4a442c41abe81e869877c0f999ee0 to your computer and use it in GitHub Desktop.
$psi = [System.Diagnostics.ProcessStartInfo]@{
UseShellExecute = $false
RedirectStandardError = $true
RedirectStandardOutput = $true
FileName = 'powershell.exe'
Arguments = '$host.UI.WriteLine(''stdout''); $host.UI.WriteErrorLine(''stderr''); Start-Sleep -Seconds 5'
}
$proc = [System.Diagnostics.Process]::new()
$proc.StartInfo = $psi
Register-ObjectEvent -InputObject $proc -EventName OutputDataReceived -SourceIdentifier Process.Stdout -Action {
"STDOUT: $($EventArgs.Data)"
} | Out-Null
Register-ObjectEvent -InputObject $proc -EventName ErrorDataReceived -SourceIdentifier Process.Stderr -Action {
"STDERR: $($EventArgs.Data)"
} | Out-Null
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