Skip to content

Instantly share code, notes, and snippets.

@rgl
Created January 6, 2018 08:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rgl/4a4581a1ecbe842f67f28085144a277d to your computer and use it in GitHub Desktop.
Save rgl/4a4581a1ecbe842f67f28085144a277d to your computer and use it in GitHub Desktop.
Run a process and capture its stdout and stderr to a file
# 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