I have created a Powershell routine for setting mp3 tags on songs, where I'd like some of my parameters to act as either a regular expession or a "simple" string. To be specific, if the parameter can be said to work as a regular expression, the function should try to use this for retrieving its value; if it can't, it should simply use that value.
I've just browsed Parameter sets, and don't think this would suit me since I want to be flexible with the parameter handling; i.e. I'd like several parameters to act this way independently. But maybe I'm wrong in this? Anyway, help would be a开发者_如何转开发ppreciated.
You don't really need the try/catch if you use:
IF ($string -as [regex])
If the cast is successful it will return the regex, if not it will return $null, so used as a boolean test in the IF, it will be $true if it is a valid regex, and $false if it is not.
That being said, the I'd agree with Joey that you should settle on a single match type (either wildcard or regex) and stick with that. There's too much potential for unintended consequences in trying to determine if a regex metacharacter was intended to be match literally or not.
You can try converting the string to a regular expression and look for failures. If there is an exception, just use it as string:
$isParamRegex = $(try { $null = [regex]$Param; $true } catch { $false })
As for the parameter type, just make it a string
and document it appropriately.
However, I'd say you might want to go a different route there:
- Either make the argument always a regex, to avoid surprises with metacharacters.
- Or make it a pattern for
-like
instead of-match
which is a bit more predictable for users (imho). - In both cases provide a
LiteralParam
argument, akin toLiteralPath
to just pass things as plain strings which are handled as such.
精彩评论