Powershell: Execute a process and capture STDOUT and STDERR

Hi,

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 🙂

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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

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

Michael

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