PowerShell 中参数的自定义错误 [英] Custom error from parameters in PowerShell

查看:16
本文介绍了PowerShell 中参数的自定义错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以让 ValidateScript 在测试失败时生成自定义错误消息,例如 Test-Path?

Is it possible to have ValidateScript generate a custom error message when a test fails, like say Test-Path?

取而代之的是:

测试文件夹:无法验证参数文件夹"上的参数.值为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 变量中报告:

It would be nice to have it report this instead in the $Error variable:

找不到文件夹",可能是网络问题?

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."
    }
})]

这会给你一个这样的消息:

That will give you a message like this:

测试文件夹:无法验证参数文件夹"上的参数.不能找到路径 '\serverTempasdf' 因为它不存在.也许有网络问题?

Test-Folder : Cannot validate argument on parameter 'Folder'. Cannot find path '\serverTempasdf' because it does not exist. Maybe there are network issues?

或者:

测试文件夹:无法验证参数文件夹"上的参数.路径'\serverTempasdf' 不是容器.

Test-Folder : Cannot validate argument on parameter 'Folder'. The path '\serverTempasdf' 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆