Skip to content

Instantly share code, notes, and snippets.

@JackGruber
Created May 11, 2018 17:12
Show Gist options
  • Save JackGruber/142863ba8c76132d7b704b5decb8a8a8 to your computer and use it in GitHub Desktop.
Save JackGruber/142863ba8c76132d7b704b5decb8a8a8 to your computer and use it in GitHub Desktop.
Execute a process and return the output from standard output and standard error
function Get-ProcessOutput
{
Param (
[Parameter(Mandatory=$true)]$FileName,
$Args
)
$process = New-Object System.Diagnostics.Process
$process.StartInfo.UseShellExecute = $false
$process.StartInfo.RedirectStandardOutput = $true
$process.StartInfo.RedirectStandardError = $true
$process.StartInfo.FileName = $FileName
if($Args) { $process.StartInfo.Arguments = $Args }
$out = $process.Start()
$StandardError = $process.StandardError.ReadToEnd()
$StandardOutput = $process.StandardOutput.ReadToEnd()
$output = New-Object PSObject
$output | Add-Member -type NoteProperty -name StandardOutput -Value $StandardOutput
$output | Add-Member -type NoteProperty -name StandardError -Value $StandardError
return $output
}
$output = Get-ProcessOutput -FileName "cmd.exe" -Args "/c ping localhost"
Write-Host -ForegroundColor green $output.StandardOutput
Write-Host -ForegroundColor red $output.StandardError
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment