Skip to main content

Elegant PowerShell function that encapsulates the execution and error handling of running an external command within a script. The function will exit the executing script on error and report the appropriate error from the failed command.

#
# Terrminate the script when a command fails, reporting the error (v1).
#
# NOTE: remember to surround executables with braces, e.g.: `Exec { ... }`
#
# Original: http://jameskovacs.com/2010/02/25/the-exec-problem/
function Exec([scriptblock]$cmd, [string]$errorMessage = "Error executing command: " + $cmd) {
    & $cmd
    if ($LastExitCode -ne 0) {
        throw $errorMessage
    }
}

#
# Terrminate the script when a command fails, reporting the error (v2).
#
# Handy function for executing a command in powershell and throwing if it
# fails.
#
# NOTE: remember to surround executables with braces, e.g.: `Exec { ... }`
#
# Modified: https://github.com/dotnet/roslyn/blob/master/build/scripts/build-utils.ps1
function Exec2([scriptblock]$cmd, [string]$errorMessage = "Error executing command: " + $cmd) {
    $output = & $cmd
    if (-not $?) {
        Write-Host $output
        throw $errorMessage
    }
}

#
# Usage:
#

# v1
'Starting script...'
$ErrorActionPreference = 'Stop'
Exec { ping -badoption }
rm nonexistent.txt
'Finished script'

# v2
Exec2 { & (Join-Path $PSScriptRoot "download-nuget.ps1") }