Last active
March 2, 2023 00:50
-
-
Save ConanChiles/5a629c803393559e884984dfd0b2a498 to your computer and use it in GitHub Desktop.
PowerShell ProcessStartInfo stdout stderr
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
Set-StrictMode -Version 'latest' | |
$ErrorActionPreference = 'stop' | |
$ProcessStartInfo = [System.Diagnostics.ProcessStartInfo]::new() | |
$ProcessStartInfo.FileName = 'C:\Windows\System32\cmd.exe' | |
$ProcessStartInfo.Arguments = '/c echo normal boring standard out && echo this is the error message 1>&2' | |
$ProcessStartInfo.CreateNoWindow = $true | |
$ProcessStartInfo.UseShellExecute = $false | |
$ProcessStartInfo.RedirectStandardOutput = $true | |
$ProcessStartInfo.RedirectStandardError = $true | |
$Process = [System.Diagnostics.Process]::new() | |
$Process.StartInfo = $ProcessStartInfo | |
[void]$Process.Start() | |
$Process.WaitForExit() | |
Write-Host | |
'stdout:' | Write-Host -ForegroundColor Cyan | |
$Process.StandardOutput.ReadToEnd() | Write-Host | |
Write-Host | |
'stderr:' | Write-Host -ForegroundColor Red | |
$Process.StandardError.ReadToEnd() | Write-Host | |
<# this works, but the above produces cleaner output | |
$sbSomeError = [scriptblock]::Create({ | |
"some normal boring stdout" | Write-Output | |
"some error message" | Write-Error | |
}) | |
$ProcessStartInfo.FileName = 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe' | |
$ProcessStartInfo.Arguments = "-NonInteractive -EncodedCommand `"$([System.Convert]::ToBase64String( [System.Text.Encoding]::Unicode.GetBytes($sbSomeError.ToString()) ))`"" | |
#> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment