Skip to content

Instantly share code, notes, and snippets.

@bender-the-greatest
Last active October 8, 2020 07:17
Show Gist options
  • Save bender-the-greatest/692882282f46b38bc09d9338253723a2 to your computer and use it in GitHub Desktop.
Save bender-the-greatest/692882282f46b38bc09d9338253723a2 to your computer and use it in GitHub Desktop.
Invoke an external command and check the result
function Invoke-Executable {
[CmdletBinding()]
Param(
[Parameter(Mandatory, Position=0)]
[string]$Command,
[Parameter(Position=1, ValueFromRemainingArguments)]
[string[]]$Arguments,
[int[]]$ExitCode = 0
)
try {
Write-Verbose "Running command: ${Command} $($Arguments -join ' ')"
& $Command @Arguments
} catch [System.Management.Automation.CommandNotFoundException] {
$message = "Command ${Command} not found. If an argument is mistaken for a named parameter of this function, prefix positional arguments with --. ",
"`te.g. ``Invoke-Executable ping -- www.google.com -c 2``" -join [System.Environment]::NewLine
throw [System.Management.Automation.RuntimeException]::new([string]$message, $_.Exception)
}
if( $LASTEXITCODE -notin $ExitCode ) {
Write-Error "Command failed with exit code ${LASTEXITCODE}. Use -ExitCode to specify expected exit codes."
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment