Alternative to Throwing Param Exceptions in PowerShell?

五迷三道 提交于 2019-12-25 05:17:27

问题


Bottom Line Up Front

I'm looking for a method to validate powershell (v1) command line parameters without propagating exceptions back to the command line.

Details

I have a powershell script that currently uses param in conjunction with [ValidateNotNullOrEmpty] to validate command line paramaters:

param(
   [string]
   [ValidateNotNullOrEmpty()]$domain = $(throw "Domain (-d) param required.")
)

We're changing the paradigm of error handling where we no longer want to pass exceptions back to the command line, but rather provide custom error messages. Since the param block can not be wrapped in a try catch block, i've resorted to something like the following:

param(
   [string]$domain = $("")
)
Try{
   if($domain -like $("")){
      throw "Domain (-d) param required."
    }
...

}Catch{
#output error message 
}

My concern is that we're bypassing all of the built-in validation that is available with using param. Is my new technique a reasonable solution? Is there a better way to validate command line params while encapsulating exceptions within the script? I'm very much interested in see how PowerShell professionals would handle this situation.

Any advice would be appreciated.


回答1:


As I mentioned in a comment: more I read your description, more I come to the conclusion that you should not worry about "bypassing all built-in validation". Why? Because that's exactly your target. You want to bypass it's default behavior, so if that's what you need and have to do - than just do it. ;)




回答2:


One way is to use default parameters like this [from msdn] -

Function CheckIfKeyExists 
{ 
    Param( 
        [Parameter(Mandatory=$false,ValueFromPipeline=$true)] 
        [String] 
        $Key = 'HKLM:\Software\DoesNotExist' 
    ) 
    Process 
    { 
        Try 
        { 
            Get-ItemProperty -Path $Key -EA 'Stop' 
        } 
        Catch 
        { 
            write-warning "Error accessing $Key $($_.Exception.Message)"   
        } 
    } 
}

So, here, if you try calling the function without passing any parameters, you will get warning what you have defined in your try/catch block. And, you are not using any default validation attributes for that. You should always assume that you will encounter an error, and write code that can survive the error. But the lesson here is if you implement a default value, remember that it is not being validated.

Read more here




回答3:


You can write a custom validation script. Give this parameter a try.

Param(
    [ValidateScript({
        If ($_ -eq $Null -or $_ -eq "") {
            Throw "Domain (-d) param required."
        }
        Else {
            $True
        }
    })][string]$Domain
)


来源:https://stackoverflow.com/questions/11022170/alternative-to-throwing-param-exceptions-in-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!