Using The ValidatePattern PowerShell Parameter Attribute

Ever need to ensure that a PowerShell function parameter matches a specific regular expression? If so, you’re in luck! Check out this video by Josh King as he shows how to use the ValidatePattern parameter attribute in PowerShell to do just that.

Powershell's validate pattern validation attribute allows you to specify a regular expression. To be compared against the values being provided to your parameters or variables. In this example function I'm using the validate pattern attribute. To ensure that the values being provided to my good parameter are indeed a valid good. You can see the regular expression within the parentheses. And also note that in Visual Studio Code. This is currently causing the syntax highlighter, some issues in syntax highlighting. But rest assured, that the code is valid and correct. When I run this function. Providing an integer. Against my GUID parameter. I get an error message stating that it doesn't match the pattern. And if I provide a string fake dash GUID. I also receive an error because it's not a valid GUID. If however, I generate a new GUID using the new GUID commander. The function completes successfully because the value being provided to my parameter is a valid GUID, which we can see. Here. It's also possible to use this attribute outside of a function. To validate the contents of a variable? In this example. Of specified the validate pattern attribute again within square brackets. Then within the parentheses you can see a regular expression. This one is validating that. The value is a valid email address. Then. I'm naming my variable in this case email. And then on, providing a value to that variable. When I run this. It completes successfully as I've provided a valid email address. If however, I make this malformed. By getting rid of the at symbol. I get an error. That Spain, the validate pattern attribute. Thank you for watching.