MegaBites-AI/Windows-powershell
0372
1# Copyright (c) Microsoft Corporation.2# Licensed under the MIT License.3 4# this function wraps native command Execution5# for more information, read https://mnaoumov.wordpress.com/2015/01/11/execution-of-external-commands-in-powershell-done-right/6function script:Start-NativeExecution {7 param(8 [Alias('sb')]9 [Parameter(Mandatory=$true)]10 [scriptblock]$ScriptBlock,11 [switch]$IgnoreExitcode,12 [switch]$VerboseOutputOnError13 )14 15 $backupEAP = $ErrorActionPreference16 $ErrorActionPreference = "Continue"17 Write-Verbose "Executing: $ScriptBlock"18 try {19 $cwd = Get-Location20 21 if ($VerboseOutputOnError.IsPresent) {22 $output = & $ScriptBlock 2>&123 } else {24 & $ScriptBlock25 }26 27 # note, if $ScriptBlock doesn't have a native invocation, $LASTEXITCODE will28 # point to the obsolete value29 if ($LASTEXITCODE -ne 0 -and -not $IgnoreExitcode) {30 if ($VerboseOutputOnError.IsPresent -and $output) {31 $output | Out-String | Write-Verbose -Verbose32 }33 34 # Get caller location for easier debugging35 $caller = Get-PSCallStack -ErrorAction SilentlyContinue36 if ($caller) {37 $callerLocationParts = $caller[1].Location -split ":\s*line\s*"38 $callerFile = $callerLocationParts[0]39 $callerLine = $callerLocationParts[1]40 41 $errorMessage = "Execution of {$ScriptBlock} in '$cwd' by ${callerFile}: line $callerLine failed with exit code $LASTEXITCODE"42 throw $errorMessage43 }44 throw "Execution of {$ScriptBlock} in '$cwd' failed with exit code $LASTEXITCODE"45 }46 } finally {47 $ErrorActionPreference = $backupEAP48 }49}50 