Custom error from parameters in PowerShell

后端 未结 4 2035
夕颜
夕颜 2020-12-17 14:25

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

Instead of this:

4条回答
  •  遥遥无期
    2020-12-17 15:20

    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:

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

    Or:

    Test-Folder : Cannot validate argument on parameter 'Folder'. The path '\\server\Temp\asdf' is not a container.

    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}"
    }
    

    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
    

提交回复
热议问题