Recently I was working on a PowerShell script with many custom functions. When I started to use PowerShell custom objects I wanted to be able to pass them to a function. So I faced the challenge of validating my object for all required properties and came up with this solution, using the ValidateScript block to test the object:
Customizing the ValidateScript#
As you can see I use a ValidateScript for the parameter validation to test the object for the required properties. The properties can be specified in an array:
$requiredProperties=@("Property1","Property2","Property3", "Property4")
When we call the Function with an appropriate object:
1
2
3
4
5
6
| $config= [PSCUSTOMOBJECT]@{
property1= "Value";
property2= "Value";
property3= "Value";
property4= "Value";
}
|
We receive the following output:
1
2
| PS H:\> New-Example -InputObject $config
Succesfully passed ValidateScript
|
Result#
If we remove one or more properties from our custom object, an error is thrown:
1
2
3
4
5
6
7
8
9
| PS H:\> $config= [PSCUSTOMOBJECT]@{
property1= "Value";
property2= "Value";
property3= "Value";
}
New-Example -InputObject $config
New-Example : Cannot validate argument on parameter 'InputObject'. Property: 'Property4' missing At line:10 char:26 + New-Example -InputObject $config + ~~~~~~~ + CategoryInfo : InvalidData: (:) [New-Example], ParameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationError,New-Example
|
If you want to go a step further you could extend the ValidateScript to…
Prevent passing properties with a NULL or empty value#
1
2
3
4
5
| $_.PSObject.Properties | ForEach-Object {
if (([string]::IsNullOrEmpty($_.Value))){
Throw [System.Management.Automation.ValidationMetadataException] "Property '$($_.Name)' has either a NULL or empty value"
}
}
|
If we call our function again with the added IsNullOrEmpty validation NULL or emtpy values throw an exception:
1
2
3
4
5
6
7
8
9
10
| PS H:\> $config= [PSCUSTOMOBJECT]@{
property1= "Value";
property2= "Value";
property3= "Value";
property4= $null;
}
New-Example -InputObject $config
New-Example : Cannot validate argument on parameter 'InputObject'. Property 'property4' has either a NULL or empty value At line:11 char:26 + New-Example -InputObject $config + ~~~~~~~ + CategoryInfo : InvalidData: (:) [New-Example], ParameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationError,New-Example
|
Final Result#
Last but not least, here’s the full function with an example object:
If you have any questions or improvements just let me know.
Happy ValidateScripting!
Reference#