This repository has been archived by the owner on Oct 28, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathExec.ps1
69 lines (59 loc) · 1.66 KB
/
Exec.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#requires -version 2.0
[CmdletBinding()]
param
(
)
$script:ErrorActionPreference = "Stop"
Set-StrictMode -Version Latest
function PSScriptRoot { $MyInvocation.ScriptName | Split-Path }
trap { throw $Error[0] }
function Invoke-NativeApplication
{
param
(
[ScriptBlock] $ScriptBlock,
[int[]] $AllowedExitCodes = @(0),
[switch] $IgnoreExitCode
)
$backupErrorActionPreference = $ErrorActionPreference
$ErrorActionPreference = "Continue"
try
{
if (Test-CalledFromPrompt)
{
$wrapperScriptBlock = { & $ScriptBlock }
}
else
{
$wrapperScriptBlock = { & $ScriptBlock 2>&1 }
}
& $wrapperScriptBlock | ForEach-Object -Process `
{
$isError = $_ -is [System.Management.Automation.ErrorRecord]
"$_" | Add-Member -Name IsError -MemberType NoteProperty -Value $isError -PassThru
}
if ((-not $IgnoreExitCode) -and (Test-Path -Path Variable:LASTEXITCODE) -and ($AllowedExitCodes -notcontains $LASTEXITCODE))
{
throw "Execution failed with exit code $LASTEXITCODE"
}
}
finally
{
$ErrorActionPreference = $backupErrorActionPreference
}
}
function Invoke-NativeApplicationSafe
{
param
(
[ScriptBlock] $ScriptBlock
)
Invoke-NativeApplication -ScriptBlock $ScriptBlock -IgnoreExitCode | `
Where-Object -FilterScript { -not $_.IsError }
}
function Test-CalledFromPrompt
{
(Get-PSCallStack)[-2].Command -eq "prompt"
}
Set-Alias -Name exec -Value Invoke-NativeApplication
Set-Alias -Name safeexec -Value Invoke-NativeApplicationSafe