Skip to content

Instantly share code, notes, and snippets.

@jburditt
Last active September 12, 2023 15:20
Show Gist options
  • Save jburditt/95796e5df7afe90d4c0fb7c8c47c1efc to your computer and use it in GitHub Desktop.
Save jburditt/95796e5df7afe90d4c0fb7c8c47c1efc to your computer and use it in GitHub Desktop.
Powershell Stop on error and silence warnings
function Invoke-Call {
param (
[scriptblock]$ScriptBlock,
[string]$ErrorAction = $ErrorActionPreference,
[string]$WarningAction = $WarningPreference
)
$WarningPreference = $WarningAction
& @ScriptBlock
if (($lastexitcode -ne 0) -and $ErrorAction -eq "Stop") {
exit $lastexitcode
}
}
Invoke-Call -ScriptBlock {
Write-Warning 'foo'
Write-Warning 'bar'
Write-Output 'test'
} -ErrorAction Stop -WarningAction SilentlyContinue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment