Last active
October 8, 2020 07:17
-
-
Save bender-the-greatest/692882282f46b38bc09d9338253723a2 to your computer and use it in GitHub Desktop.
Invoke an external command and check the result
This file contains hidden or 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 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