Oscar Foley
Oscar Foley

Reputation: 7025

How to escape characters inside of a parameter in Powershell?

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?

Upvotes: 2

Views: 4161

Answers (1)

briantist
briantist

Reputation: 47792

[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.

Upvotes: 7

Related Questions