Using PowerShell Null Validation Parameter Attributes
Think you can do better? Show us!
In this video, Josh will explain how two PowerShell parameter attributes ValidateNotNull and ValidateNotNullorEmpty work.
Powershell's validate not null validation attribute allows you to specify that the values being assigned to a parameter or variable cannot be null. Powershell will generate an error if these values are found to be null. In this example function. I'm using the validate not null attribute in square brackets with empty parentheses to specify that my not null parameter will not accept null input. If I run this function and supply a string it will run. However, if that parameter receives null it will generate an error. This is useful when accepting pipeline input from other functions is that other function might output a null value that you weren't expecting and this means you don't have to write test cases for that eventuality. However, note that this parameter will accept an empty string. To not accept an empty string, you can use the validate not null or empty validation attribute and it is very similar to the not null attribute in that you specify it against your parameter with square brackets and empty parentheses. The difference being that it will not accept an empty string. It will also not accept null but it will accept anything else. It's possible to use both of these validation attributes outside of functions to test the value being assigned to a variable and in this case. I am using validate not null or empty to test the value being assigned to computer name via the read host cmdlet. When I run this, I'm prompted to enter my name and when I enter Josh that's accepted. However, if I run this again and simply press enter supplying an empty string. I'm told that this is not a valid case. That was the validate not null and validate not null or empty validation attributes. Thank you for watching.