I have a Powershell script using a -like to do a value comparison. I can write the regex using traditional regex methods and it works in the online testers I’ve used but I cannot get it to work in my script. I suspect it’s simply a syntax thing but all the sites I’ve referenced don’t address scripting specifically.
I’m checking namespaces to see if there are matches. For example,
www.domain.com
www.itdomain.com
www.anotherdomain.com
www.somedomain.com
In this example, I’d like to match only the first two options. This regex works at the tester mentioned above,
\.(it)?domain\.
Writing this in my script adds a small complication because the value "domain" is in a variable, so I’ve tried,
$domainUrl -like "*.(it)?$($domain).*" but the results are always false.
What am I missing in the Powershell syntax?
>Solution :
The -like operator matches against wildcard patterns, not regexes.
You want the -match operator.
Your pattern, "*.(it)?$($domain).*", is actually a mix of these two pattern languages, which won’t work.
Presumably, you meant something like the following:
$domain = 'domain'
'www.itdomain.com' -match "\.(it)?$domain\." # -> $true
Note that -match – unlike -like – matches substrings by default, so there’s no need to consume the input string as a whole with a given regex.
That is, the above matches a literal . (which must be escaped as \. in a regex) followed by either itdomain or domain ((it)? matches it if present (?)) and another literal . anywhere in the input string. For details, see this regex101.com page.
(The regex could be refined to make the matching more robust.)
For details on -like (wildcards) vs. -match (regexes), see this answer.