Quick tip: Validating powershell parameters

Although powershell offers a great way of validating the parameters using advanced functions we can extend this functionality to make simple scripts robust as they can be

http://technet.microsoft.com/en-us/library/hh847743.aspx

for example here in this snipet we can validate the input string using a pattern and length

1
2
3
4
5
6
7
8
9
 Param
          (
            [parameter(Mandatory=$true)]
            [ValidateLength(5,10)]
            [String]
            $str
          ) 
$str

Above script will make sure input string length is at least 5 charcters upt 10 characters max

validate input
input string test less than 5 charecters script throws an exception

validate input 1

[ValidatePattern(“[A-Z][A-Z][A-Z][A-Z][A-Z][A-Z]”)]

adding this as a validation attriubute this will make sure string only contains letters a to z

 Param
          (
            [parameter(Mandatory=$true)]
            [ValidateLength(5,10)]
	    [ValidatePattern("[A-Z][A-Z][A-Z][A-Z][A-Z][A-Z]")]
            [String]
            $str
          ) 

$str

validate pattern

 

we can also validate from a script this what I am really interested

below is a simple function that checks if a parameter is null or empty if its not empty does it has any whitespaces similar a static method .Net 4 exposes IsNullOrWhiteSpace

 

function Isnullorempty ($str) 
{
IF( $str -eq $null ) 
 {  $true }  
elseif ( $str.ToString().Trim().Length -eq  0 ){ $true}
else {$false}
}

We are going to embed this script in validation script

 Param
          (
            [parameter(Mandatory=$true)]
            [ValidateLength(5,10)]
 	    [ValidateScript({ IF( $_ -eq $null) 
		{$false }  
	    elseif ($_.ToString().Trim().Length -eq  0 )
		{$false}
	    else {$true}} )]
            [String]$str
          ) 

$str

 

If run with blank white sure it throws an error

PS C:\Powershell> .\powershell.ps1 ” ”
C:\Powershell\powershell.ps1 : Cannot validate argument on parameter ‘str’.
The ” IF( $_ -eq $null)
{$false }
elseif ($_.ToString().Trim().Length -eq 0 )
{$false}
else {$true}” validation script for the argument with value ”
” did not return true. Determine why the validation script
failed and then try the command again.
At line:1 char:19
+ .\powershell.ps1 ” ”
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [powershell.ps1], ParameterBind
ingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,powershell.ps1

PS C:\Powershell> .\powershell.ps1  test1
test1

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s