Artem Bokov
Artem Bokov

Reputation: 332

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?

Upvotes: 2

Views: 1169

Answers (3)

c z
c z

Reputation: 9027

Handling is via Write-Error:

    function test1 {
        [CmdletBinding()]
        param()
        Write-Error "blah blah blah"
    }
  • Write-Error will throw when $ErrorActionPreference is Stop, ask the user for Inquire, print and continue for Continue, etc. etc.

More advanced handling is via:

  • throw, which will, by contrast, always halt execution.
  • $ErrorActionPreference, which holds the current state of the cascading -ErrorAction value.

Upvotes: 0

smichaud
smichaud

Reputation: 326

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

Upvotes: 2

Kirill Pashkov
Kirill Pashkov

Reputation: 3236

I would suggest you to place validation events for input parameters instead, like this:

param([ValidateScript({Test-Path $_})][string]$path = "c:\temp")

Upvotes: 0

Related Questions