Last active
February 27, 2021 04:26
-
-
Save lukegackle/f33125ce9851a224715fa192563d2241 to your computer and use it in GitHub Desktop.
Redirect standard output in PowerShell or standard error output, allowing you to capture output from another program in PowerShell. https://lukestoolkit.blogspot.com/2021/02/redirect-standard-output-from-external.html
This file contains 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
# Setup redirection | |
$StartInfo = New-Object System.Diagnostics.ProcessStartInfo -Property @{ | |
FileName = "$env:SystemRoot\System32\ping.exe" | |
Arguments = "127.0.0.1" | |
UseShellExecute = $false | |
RedirectStandardOutput = $true #If true redirects standard output from the application | |
RedirectStandardError = $true #If true redirects error output from the application | |
CreateNoWindow = $true #Should the process create its own window? Or should it be hidden? | |
} | |
#Create process Object | |
$Process = New-Object System.Diagnostics.Process | |
#Assign the process parameters | |
$Process.StartInfo = $StartInfo | |
# Register Object Events to Receive Output | |
$OutEvent = Register-ObjectEvent -Action { | |
if($Event.SourceEventArgs.Data -like "Reply from*"){ | |
Write-Host "New Data" -ForegroundColor Cyan | |
Write-Host $Event.SourceEventArgs.Data | |
} | |
} -InputObject $Process -EventName OutputDataReceived | |
$ErrEvent = Register-ObjectEvent -Action { | |
if($Event.SourceEventArgs.Data -ne $null){ | |
Write-Host "Error" -ForegroundColor Red | |
Write-Host $Event.SourceEventArgs.Data | |
} | |
} -InputObject $Process -EventName ErrorDataReceived | |
$ExitEvent = Register-ObjectEvent -Action { | |
Write-Host "Finished" | |
# Unregister events | |
$OutEvent.Name, $ExitEvent.Name, $ErrEvent.Name | | |
ForEach-Object {Unregister-Event -SourceIdentifier $_} | |
} -InputObject $Process -EventName Exited | |
# Start process | |
if($Process.Start()){ | |
# Begin output redirection | |
$Process.BeginOutputReadLine() | |
$Process.BeginErrorReadLine() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment