2

This is a simplified version of my function:

function DetectLocalUser($localGroup, $members) { $result = net localgroup "$localGroup" #$members= $members.Replace("\","\\") if ($result -match $members) { return $true } else { return $false } } 

To invoke the function I use this example (Typical values I am going to receive):

DETECTLocalUser "test" "iis apppool\userapi" 

The parameters are not controlled by me. If they were I would escape directly the second parameter "iis apppool\\userapi"

On execution I have a problem with the \ in the parameter. The exact error is:

parsing "iis apppool\icisapi" - Unrecognized escape sequence \i. At C:\k\a.ps1:6 char:9 + if ($result -match $members) + ~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : OperationStopped: (:) [], ArgumentException + FullyQualifiedErrorId : System.ArgumentException

I found a workaround by adding #$members= $members.Replace("\","\\") fixes the problem but I am not sure if is the best option.

Is my workaroud acceptable or is there a better way of escaping $members parameter?

1 Answer 1

7
[RegEx]::Escape($members) 

That will ensure that characters in strings get interpreted as literals and not as part of the RegEx.

To explain further, the -match operator is doing a regular expression match, so the string you pass to it is interpreted as a regular expression.

Backslash happens to be the escape character in a regular expression, so that's where your issue is. Using [RegEx]::Escape() ensures that other characters won't be interpreted, such as [,],.,+,(,),^,$,?,*, etc.

Sign up to request clarification or add additional context in comments.

1 Comment

I tested it and it works perfectly. It is better than my workaround because it escapes all special characters and I don't need to recode that logic myself. TA!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.