Skip to content
mnaoumov.dev
Go back

Execution of external commands (native applications) in PowerShell done right - Part 3

Part 1, Part 2

Hi folks

I realized that my previous implementation has a flaw. I though that exit code always 0..255 but this is the case only in DOS. In Windows it can be any signed 32-bit integer. So I had to fix it. You cannot create an array with all int values in PowerShell because of out-of-memory, so I had to take a switch approach.

function Invoke-NativeApplication
{
    param
    (
        [ScriptBlock] $ScriptBlock,
        [int[]] $AllowedExitCodes = @(0),
        [switch] $IgnoreExitCode
    )

    $backupErrorActionPreference = $ErrorActionPreference

    $ErrorActionPreference = "Continue"
    try
    {
        if (Test-CalledFromPrompt)
        {
            $lines = & $ScriptBlock
        }
        else
        {
            $lines = & $ScriptBlock 2>&1
        }

        $lines | ForEach-Object -Process `
            {
                $isError = $_ -is [System.Management.Automation.ErrorRecord]
                "$_" | Add-Member -Name IsError -MemberType NoteProperty -Value $isError -PassThru
            }
        if ((-not $IgnoreExitCode) -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

I’ve also created a repository which contains all my attempts to the problem https://github.com/mnaoumov/Invoke-NativeApplication

Stay tuned!


Share this post on:

Previous Post
I raise jQuery bug for IE8
Next Post
Execution of external commands (native applications) in PowerShell done right - Part 2