如何在Advanced函数中正确使用 ErrorAction 参数?例如我有这样的功能:
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"
}
假设源路径 $ src 不存在。我正在使用 ErrorAction = Stop 执行此功能:
test1 -ea stop
我预计将引发错误,并且我会而不是看到“ SomeText ”消息。但是我明白了:
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
我可以在 test1 函数内的 Copy-Item cmdlet中添加 ErrorAction 参数,但是我希望能够将其显式设置为启用/禁用错误操作行为的功能。
我应该怎么做才能使其正常工作?
最佳答案
您需要使用$PSBoundParameters
和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