Beginning in PowerShell 5, you can create your own attributes, i.e. custom validators. They can be applied to variables (and parameters), and once a value is assigned that does not match the validator, an exception is raised.
Here is an example for a path validator. When you apply it to a variable, only valid file paths can be applied to the variable:
class ValidatePathExistsAttribute : System.Management.Automation.ValidateArgumentsAttribute
# the value to be checked surfaces in $path and must be of type [object]
# if anything is wrong with the value, throw an exception
if(-not (Test-Path -Path $path))
# if NO exception was thrown, the value is accepted
[ValidatePathExists()][string]$Path = "c:\windows"
$Path = "c:\test123"
Whenever you assign a path that does not exist, PowerShell will *not* assign it and instead keep the existing value.
ReTweet this Tip!
Powered by IDERA