Home > Enterprise >  Force a full domain name in param
Force a full domain name in param

Time:10-08

param(
    [Parameter(Mandatory = $true , HelpMessage = "Enter a domain like facebook.com")]

    [ValidateScript({
            try {

                $_ -like "*.*" 
            }
            catch {

                throw "Enter a domain like facebook.com."

            }
        })][string]$Domain
)

I am trying to learn to error check in param. I know how to do this in a if . From what I read this should work but when sent Facebook I get the error below. It works for facebook.com

error

Cannot validate argument on parameter 'Domain'. The "
            try {
                $_ -like "*.*" 
            }
            catch {
                throw "Enter a domain like facebook.com."
            }
        " validation script for the argument with value "facebook" did not return a result of True. Determine why the validation script failed,  
and then try the command again.
At line:1 char:1
  . {
  ~~~
      CategoryInfo          : InvalidData: (:) [], ParameterBindingValidationException
      FullyQualifiedErrorId : ParameterArgumentValidationError

What am I doing wrong?

CodePudding user response:

Your current try statement will not throw an error, so it will never run catch. You could also throw a better error type

Your validation script should look closer to this:

param(
  [ValidateScript({
    if ($_ -like "*.*") {
      $true
    }
    else {
      Throw [System.Management.Automation.ValidationMetadataException] "Enter a domain like facebook.com."
    }
  })][string]$Domain
)

You can use try/catch in validation scripts, but only if the actual try block returns an error

CodePudding user response:

You can use ValidatePattern with regex

 [ValidatePattern('.*\..*')]

In Powershell 7 the ErrorMessage parameter was added

 [ValidatePattern('.*\..*', ErrorMessage = "your message")]
  • Related