Using The PowerShell ValidateScript Parameter Attribute

Josh is going 6 for 6 with another PowerShell parameter validation attribute video. I think he’s got them all covered! Good job, Josh. In this one, he’s covering the ValidateScript parameter validation attribute to test whether a file passed to a parameter exists or not. So useful. Really.

Powershell validate script validation attribute allows you to specify your own code blocks to test the values being provided to your parameters and variables. In this example function. I'm using the validate script attribute within square brackets to test the strings being provided to my image path parameter. My script block is defined within parentheses and then within curly brackets and you can provide any script. You want within those curly brackets as long as you return true. If the value being tested is valid and if it isn't you either throw an error or return false. Also note that the value being tested is represented within your scriptblock as dollar underscore. In this specific example. I'm using test path, which does return either true or false and I have a number of parameters, there to ensure I only return true effort is what I would want my function to execute against. When I run this function specifying a path on my C drive that ends in a PNG file which does actually exist on my hard drive the script runs as expected. If I change the path to a GIF file on my hard drive, which doesn’t exist. I get an error message Because Dot. GIF is not a dot PNG or a dot JPG? Which my validate script is specifically looking for also, if I run against the image that doesn't exist but is one of the valid file extensions. I also receive an error because test path is returning false. It's possible to use this attribute outside of a function to test the values being provided to a variable and you do that by defining the validate script attribute again within square brackets and then you define your scriptblock within parentheses. And then square brackets again. You can define any script. You want in there as long as it returns true. If the item being tested, as valid and false or throwing an error if it isn't valid in this example, I’m using this connection. With the dash quiet parameter so that true or false is returned rather than any other information. You then define your variable in this case. I'm using DNS server and for this example. I am assigning a value to that variable using read host to get information via the terminal. So if I run this and provide a DNS server that does exist. It executes successfully if however. I execute that line again and provide a DNS server. That doesn't exist. You notice it takes a little bit longer to run because it has to fail. The echo request, but then I get an error back, saying that isn't valid for the DNS server variable. That's been the validate script attribute thank you for watching.