Reputation: 332
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
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
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
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