简体   繁体   中英

How to Escape \ backslash character in PowerShell Active Directory filter

I'm trying to filter groups in Active Directory that have a UNC in the Info field, but am having great difficulty finding how to escape the backslash character in the UNZ path. The following returns no results:

Get-ADGroup -filter 'Info -like "*\\server\share*"' -Properties Name,Info | Select Name,Info

Whereas the following does return some results, but would not be accurate if two groups had similar UNC paths:

Get-ADGroup -filter 'Info -like "*server*share*"' -Properties Name,Info | Select Name,Info

I've tried using \5c , \u5c , [char]0x25 , `u{5c} , *\\\\server\\path* , *`\`\server`\path* all without success, and have run out of ideas and search results to try.

Use the -LDAPFilter parameter, then substitute all literal backslashes with the escape sequence \5C :

Get-ADObject -LDAPFilter '(info=*\5C\5Cserver\5Cshare*)'

You could write a generic function to take care of escaping string values:

function ConvertTo-LDAPFilterString
{
  param(
    [string]$Value
  )

  $charsToEscape = "\*()`0".ToCharArray()

  foreach($char in $charsToEscape){
    $escapeSequence = '\{0:X2}' -f +$char
    $Value = $Value.Replace("$char", $escapeSequence)
  }

  return $Value
}

Now you can do:

$escapedPath = ConvertTo-LDAPFilterString '\\server\share'
Get-ADObject -LDAPFilter "(info=*$escapedPath*)"

As to why that is, it's not specific to Active Directory, but part of the design of LDAPv3.

RFC 4515 § 3 describes the correct grammar of LDAPv3 filter strings, which includes something called "the value-encoding rule":

[...] the octets that represent the ASCII characters "*" (ASCII 0x2a), "(" (ASCII 0x28), ")" (ASCII 0x29), "\" (ASCII 0x5c), and NUL (ASCII 0x00) are represented as a backslash "\" (ASCII 0x5c) followed by the two hexadecimal digits representing the value of the encoded octet.

The reason for this narrow and perculiar encoding rule is to allow unambiguous forward-only parsing of filter strings - a \ in the value part of a clause is always the start of a fixed-length escape sequence because a literal \ would also have been encoded as a fixed-width escape sequence:)

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