来自PowerShell中参数的自定义错误 [英] Custom error from parameters in PowerShell
问题描述
如果测试失败,例如Test-Path
,是否可以让ValidateScript
生成自定义错误消息?
Is it possible to have ValidateScript
generate a custom error message when a test fails, like say Test-Path
?
代替此:
Test-Folder:无法验证参数'Folder'上的参数.参数"blabla"的参数的"Test-Path $ _ -Path Type Container"验证脚本未返回True的结果.确定验证脚本失败的原因,然后再次尝试逗号.
Test-Folder : Cannot validate argument on parameter 'Folder'. The "Test-Path $_ -Path Type Container" validation script for the argument with value "blabla" did not return a result of True. Determine why the validation script failed, and then try the comma and again.
最好在$Error
变量中报告它:
找不到文件夹",也许是网络问题?
The 'Folder' is not found, maybe there are network issues?
代码:
Function Test-Folder {
Param (
[parameter(Mandatory=$true)]
[ValidateScript({Test-Path $_ -PathType Container})]
[String]$Folder
)
Write-Host "The folder is: $Folder"
}
解决方法1:
我可以删除Mandatory=$true
并进行如下更改.但这并不能为我提供正确的Get-Help
语法,也不会进行Test-Path
验证,因为它只会检查参数是否存在.
I could remove the Mandatory=$true
and change it as below. But this doesn't give me the correct Get-Help
syntax and doesn't do the Test-Path
validation, because it only checks if the parameter is present.
Function Test-Folder {
Param (
[parameter()]
[String]$Folder = $(throw "The $_ is not found, maybe there are network issues?")
)
Write-Host "The folder is: $Folder"
}
解决方法2:
I found this workaround on a blog post, but the problem is that it generates two errors instead of one.
Function Test-Folder {
Param (
[parameter(Mandatory=$true)]
[ValidateScript({
if (Test-Path $_ -PathType Container) {$true}
else {Throw "The $_ is not found, maybe there are network issues?"}})]
[String]$Folder
)
Write-Host "The folder is: $Folder"
}
解决方法3:
我可以也可以尝试通过添加评论部分来使其更加清晰.但是,这仍然不是理想的结果,因为最终用户需要可以读取该错误.
I could also try to make it more clear by adding a comment section. However, this is still not the desired result as the error needs to be readable to end users.
Function Test-Folder {
Param (
[parameter(Mandatory=$true)]
[ValidateScript({
# The folder is not found, maybe there are network issues?
Test-Path $_ -PathType Container})]
[String]$Folder
)
Write-Host "The folder is: $Folder"
}
推荐答案
您的ValidateScript
应该看起来像这样:
Your ValidateScript
should look something like this:
[ValidateScript({
try {
$Folder = Get-Item $_ -ErrorAction Stop
} catch [System.Management.Automation.ItemNotFoundException] {
Throw [System.Management.Automation.ItemNotFoundException] "${_} Maybe there are network issues?"
}
if ($Folder.PSIsContainer) {
$True
} else {
Throw [System.Management.Automation.ValidationMetadataException] "The path '${_}' is not a container."
}
})]
这会给您这样的消息:
Test-Folder:无法验证参数'Folder'上的参数.不能 找到路径"\\ server \ Temp \ asdf",因为它不存在.也许有 网络问题?
Test-Folder : Cannot validate argument on parameter 'Folder'. Cannot find path '\\server\Temp\asdf' because it does not exist. Maybe there are network issues?
或者:
Test-Folder:无法验证参数'Folder'上的参数.路径 '\\ server \ Temp \ asdf'不是容器.
Test-Folder : Cannot validate argument on parameter 'Folder'. The path '\\server\Temp\asdf' is not a container.
如果旧版本的PowerShell引发双重错误,则可能需要在函数内部进行测试:
If the older versions of PowerShell are throwing a double error, you may need to test inside the function:
Function Test-Folder {
Param (
[parameter(Mandatory=$true)]
[String]$Folder
)
try {
$Folder = Get-Item $_ -ErrorAction Stop
} catch [System.Management.Automation.ItemNotFoundException] {
Throw [System.Management.Automation.ItemNotFoundException] "The '${Folder}' is not found, maybe there are network issues?"
}
if (-not $Folder.PSIsContainer) {
Throw [System.Management.Automation.ApplicationFailedException] "The path '${_}' is not a container."
}
Write-Host "The folder is: ${Folder}"
}
我在PowerShell中一直讨厌的部分是试图找出要捕获的错误;该如何解决?没有抓住一切.自从我终于弄清楚了,这是怎么做的:
The part that I always hated in PowerShell was trying to figure out what error to catch; without catching all. Since I finally figure it out, here's how:
PS > Resolve-Path 'asdf'
Resolve-Path : Cannot find path '.\asdf' because it does not exist.
At line:1 char:1
+ Resolve-Path 'asdf'
+ ~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (asdf:String) [Resolve-Path], ItemNotFoundE
xception
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.ResolvePathCommand
PS > $Error[0].Exception.GetType().FullName
System.Management.Automation.ItemNotFoundException
这篇关于来自PowerShell中参数的自定义错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!