I like the idea of creating constants (read-only variables) for data that will not change in a script. However, I have not been able to figure out how to cast a constant. For instance, I want to declare a regex pattern at the beginning of a script that I may use in several places.
New-Variable -Name p -Value “regex(#\d+)” -Description “REGEX pattern for matching numbered processes” -Force -Option ReadOnly
This give the appearance of working. However, when I do a $p.gettype() it shows as a string. This is true whether I put the double-quote to the left or the right of the [regex] declaration.
I have no problems casting this string as a regex in a regular variable. I’d just like to be able to create a constant here.
You can create custom PSObjects help New-Object -Full, you can create read only variables. new-variable -name max -value 256 -option readonly
Variables also have scope you can set “Global”, “Local”, or “Script”
However I am not 100 % certain about regular expressions in PowerShell but I don’t think it is type casting the object class type I think it is still a string. I think that the [regex] operator simply tells PowerShell to try and interpret what follows as a regular expression. I think the type is still a string. Much like the [datetime]“12/1/1967” allows us enter a PowerShell data time class object in a way that is easy for us and converts it to a date and time object. Here are some links that may help, but honestly is still a little over my head. . .
You have two problems with your current code. 1) Your [regex] cast operator is inside the quotation marks, instead of outside. 2) You need to place the whole value expression inside parentheses. This forces PowerShell to use expression mode parsing instead of argument mode (see Get-Help about_Parsing).
Try this:
New-Variable -Name p -Value ([regex]“(?‘root’(\w+(\s\w+)*))(#\d+)”) -Description “REGEX pattern for matching numbered processes” -Force -Option ReadOnly
Thanks Dave. The paren fixed it. In the OP I mentioned putting [regex] inside and outside the quotes. I had even tried a sub-expression. But wrapping the whole thing in parentheses did the trick.
[regex] is a type accelerator for System.Text.RegularExpressions.Regex . It’s what does the work behind the scenes when you use things like the -match and -replace operators in PowerShell.