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 🙂

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"

Michael

Advertisment to support michlstechblog.info

Time limit is exhausted. Please reload CAPTCHA.

Original Theme by Schiy · Powered by WordPress