Created
May 11, 2018 17:12
-
-
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
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
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