Powershell to find users based on email containing apostrophe

Viewed 43

I'm trying to find Active Directory users based on their email address, when the email address contains an apostrophe, it fails to find that user. See below for command and error:

Script:

$PilotUsers = Get-Content "C:\Scripts\UPNUpdate\Users.csv" | ForEach-Object {get-aduser -Properties emailaddress -Filter "emailaddress -eq '$_'"}

ERROR: (Finds all users except users with apostrophe in their email address)

get-aduser : Error parsing query: 'emailaddress -eq 'SAMUEL.O'BOYLE@DOMAIN.UK'' Error Message: 'syntax error' at position: '27'. At line:1 char:70

  • ... ach-Object {get-aduser -Properties emailaddress -Filter "emailaddress ...
  •             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    • CategoryInfo : ParserError: (:) [Get-ADUser], ADFilterParsingException
    • FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADFilterParsingException,Microsoft.ActiveDi rectory.Management.Commands.GetADUser
1 Answers

Any ' contained in the value of $_ predictably breaks the syntax of your filter string, as the error message suggests: emailaddress -eq 'SAMUEL.O'BOYLE@DOMAIN.UK' is a syntax error, because the ' after SAMUEL.O syntactically closes the '...' string prematurely.

There are three solution options:

  • Simplest, though conceptually fraught: Use a verbatim string ('...') and rely on the AD provider to process the $_ variable reference (which then doesn't require quoting):

    • Note: This only works with stand-alone variable references, not also with expressions (e.g., $_.foo), and fundamentally doesn't work if the AD cmdlets are provided via implicit remoting.
Get-ADUser -Filter 'emailaddress -eq $_'
  • A bit more verbose, but conceptually clear: As suggested by Mathias R. Jessen, use embedded "..." quoting instead of '...' inside your - of necessity - expandable string ("...").

    • Note: `" is used for escaping the embedded ", using PowerShell's escape character, the so-called backtick (`).

      • While "" works too, using `" is a good habit to form, because it is consistent with how other characters need to be escaped and because it also works in unquoted command arguments; e.g., Write-Output `"
    • This approach relies on the values of $_ never containing " characters, which is safe to assume with email addresses.

Get-ADUser -Filter "emailaddress -eq `"$_`""
  • Most generic, but complex: Escape ' characters in the variable value as '':

    • Caveat: This uses PowerShell's escaping rules, whereas it is the AD provider that interprets the filter string. One would hope that they both apply the same escaping rules in this context, but I cannot personally verify that. Do let us know if this doesn't actually work.
Get-ADUser -Filter "emailaddress -eq '$($_ -replace "'", "''")'"
Related