powershellerror-handling

How to handle powershell Advanced function ErrorAction parameter?


How can I properly use ErrorAction parameter with my Advanced function? For instance I have such function:

function test1 {
[CmdletBinding()]
param([string]$path = "c:\temp")

$src = Join-Path $path "src"
$dest = Join-Path $path "dest"

Copy-Item -Path $src $dest -Recurse -Verbose
write "SomeText"
}

Lets assume the source path $src does not exist. And I am executing this function with ErrorAction = Stop:

test1 -ea stop

I expect that the error will be thrown and I will not see "SomeText" message. But I got it:

Copy-Item : Cannot find path 'C:\temp\src' because it does not exist.
At line:5 char:1
+ Copy-Item -Path $path\src $path\dest -Recurse -Verbose
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (C:\temp\src:String) [Copy-Item], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.CopyItemCommand

SomeText

I could add ErrorAction parameter to Copy-Item cmdlet inside the test1 function, but I want to be able to explicitly set it to the function to enable/disable error action behavior.

What should I do to make it work?


Solution

  • You need to use $PSBoundParameters and alos check $ErrorActionPreference

    function test1 {
        [CmdletBinding()]
        param([string]$path = "c:\temp")
    
        $src = Join-Path $path "src"
        $dest = Join-Path $path "dest"
    
        $errorAction = $PSBoundParameters["ErrorAction"]
        if(-not $errorAction){
            $errorAction = $ErrorActionPreference
        }
    
    
        Copy-Item -Path $src $dest -Recurse -Verbose -ErrorAction $errorAction
        write "SomeText"
    }
    
    $ErrorActionPreference = 'Stop'
    test1
    
    $ErrorActionPreference = 'continue'
    test1 -ErrorAction Stop