Created
January 6, 2018 08:20
-
-
Save rgl/4a4581a1ecbe842f67f28085144a277d to your computer and use it in GitHub Desktop.
Run a process and capture its stdout and stderr to a file
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
# converts/escapes a string to a command line argument. | |
function ConvertTo-CommandLineArgument { | |
# Normally, an Windows application (.NET applications too) parses | |
# their command line using the CommandLineToArgvW function. Which has | |
# some peculiar rules. | |
# See http://msdn.microsoft.com/en-us/library/bb776391(VS.85).aspx | |
# | |
# TODO how about backslashes? there seems to be a weird interaction | |
# between backslahses and double quotes... | |
process { | |
if ($_.Contains('"')) { | |
# escape single double quotes with another double quote. | |
return '"{0}"' -f $_.Replace('"', '""') | |
} elseif ($_.Contains(' ')) { # AND it does NOT contain double quotes! (those were catched in the previous test) | |
return '"{0}"' -f $_ | |
} elseif ($_ -eq '') { | |
return '""' | |
} else { | |
return $_ | |
} | |
} | |
} | |
function Start-WrappedProcess([string]$ProcessPath, [string[]]$Arguments, [int[]]$SuccessExitCodes=@(0)) { | |
$p = Start-Process $ProcessPath ($Arguments | ConvertTo-CommandLineArgument) ` | |
-RedirectStandardOutput $env:TEMP\stdout.txt ` | |
-RedirectStandardError $env:TEMP\stderr.txt ` | |
-WindowStyle Hidden ` | |
-Wait ` | |
-PassThru | |
Write-Output (Get-Content $env:TEMP\stdout.txt,$env:TEMP\stderr.txt) | |
Remove-Item $env:TEMP\stdout.txt,$env:TEMP\stderr.txt | |
if ($SuccessExitCodes -NotContains $p.ExitCode) { | |
throw "$(@($ProcessPath)+$Arguments | ConvertTo-Json -Compress) failed with exit code $LASTEXITCODE" | |
} | |
} | |
function git { | |
Start-WrappedProcess git $Args | |
} | |
function go { | |
Start-WrappedProcess go $Args | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment