简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM