Powershell: Execute a process and capture STDOUT and STDERR


if have to execute a process or script from powershell and you have to capture the output you can use the System.Diagnostics.Process class.

I’ve written a simple function for this case 🙂

function fStartProcess([string]$sProcess,[string]$sArgs,[ref]$pOutPut)
	$oProcessInfo = New-Object System.Diagnostics.ProcessStartInfo
	$oProcessInfo.FileName = $sProcess
	$oProcessInfo.RedirectStandardError = $true
	$oProcessInfo.RedirectStandardOutput = $true
	$oProcessInfo.UseShellExecute = $false
	$oProcessInfo.Arguments = $sArgs
	$oProcess = New-Object System.Diagnostics.Process
	$oProcess.StartInfo = $oProcessInfo
	$oProcess.Start() | Out-Null
	$oProcess.WaitForExit() | Out-Null
	$sSTDOUT = $oProcess.StandardOutput.ReadToEnd()
	$sSTDERR = $oProcess.StandardError.ReadToEnd()
	$pOutPut.Value="Commandline: $sProcess $sArgs`r`n"
	$pOutPut.Value+="STDOUT: " + $sSTDOUT + "`r`n"
	$pOutPut.Value+="STDERR: " + $sSTDERR + "`r`n"
	return $oProcess.ExitCode

and a usage example

D:\> $Output=""
D:\> $iRet=fStartProcess ping.exe "-n 1 localhost" ([ref]$Output)
D:\> write-host "Exitcode: $iRet`r`n Output: $Output"


Advertisment to support michlstechblog.info

One thought on “Powershell: Execute a process and capture STDOUT and STDERR”

  1. Thank you so much! I have systems at with with PS 5.1 that the admins refuse to update (… ya I know! FFS!) and I was stuck with that problem for a long time.

    Your function works perfectly for my needs!

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload CAPTCHA.