Using The PowerShell ValidateDrive Parameter Attribute
Think you can do better? Show us!
How many of these PowerShell parameter validation attributes exist anyway? Josh knows them all! Using the ValidateDrive validation attribute, Josh is able to single-handedly prevent certain PowerShell drives from being passed to a function parameter. That Josh sure is dreamy.
Powershell's validate drive validation attribute allows you to mandate that a given path must reside on a drive that you have specified in this example function. I'm using the validate drive attribute were then square brackets to specify that the value being provided to my path parameter must reside on either. My D drive or in my current user registry hive. When I run this function referencing a path on my C drive I get an error message because the drive C is not one of my approve drives either D or current users. However, if I run this with a path on my D Drive. The function runs successfully. Likewise, if I were to run this against a path in my registry, assuming of course, that path is in the current user hive finally this also works for relative paths and it will take into account. The drive that you are currently on so I am currently on my C drive and when I pass a relative path. I get an error because yet again. I'm using my C drive, which is not a valid drive. It's important to note that this isn't testing the validity of the entire path it is only looking at the drive. It's also possible to use this validation attribute outside of functions to validate the contents of a variable. To do that specify validate drive within square brackets and then within parentheses. List your allowed drives in this case of specified the current user registry hive then specify the name of your variable in my case, current user reg and then you can assign a value to it in this case. I'm trying to assign a local machine pass from the registry. When I run this, I get an error notice that the area isn't as user friendly. Is if you were to do this within a function but now if I change this to a current user path it runs successfully that's being the validate drive attribute. Thank you for watching.