PowerShell escape single quote in the input value from file

Viewed 105

By reading the Email address from the file, querying user status in Active directory. It works if email address didn't have single quote in it. If files has Email address with quote like user's@example.com, PowerShell giving below error message.

How to escape single quote in PowerShell?

Code

Import-Csv users.csv| 
ForEach-Object{
    
    $UserStatus=Get-ADUser -Filter "EmailAddress -eq '$($_.Email)'" -properties "*"| select -Expand userAccountControl    
$_ |
Add-Member -MemberType NoteProperty -Name "starts" -Value $UserStatus -PassThru
}  |
export-csv added-filed.csv

Error message

Get-ADUser : Error parsing query: 'EmailAddress -eq 'user's@example.com'' Error Message: 'syntax error' at position: '21'.
At added-active-status.ps1:4 char:17
+ ... $UserStatus=Get-ADUser -Filter "EmailAddress -eq '$($_.Email)'" -prop ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ParserError: (:) [Get-ADUser], ADFilterParsingException
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADFilterParsingException,Microsoft.ActiveDirectory.Management.Commands.GetADUser
2 Answers

If this were about PowerShell's escaping rules, you'd have to double embedded ' chars. inside a '...' string: -Filter "EmailAddress -eq '$($_.Email -replace "'", "''")'"

However, given that it is the Get-ADUser cmdlet (its underlying provider) that interprets the content of the -Filter argument, it is probably safer to switch to using embedded "..." quoting, in which case any ' chars. in the value of $_.Email do not require escaping (the assumption is that $_.Email doesn't also have embedded " characters):

Get-ADUser -Filter "EmailAddress -eq `"$($_.Email)`""

You should be able to escape a single quote, with another. Give this a try:

Import-Csv users.csv | 
    ForEach-Object -Process {
        
        $Email = $_.Email.Split('''') -join "''"

        $UserStatus = Get-ADUser -Filter "EmailAddress -eq $Email" -properties "*"| select -Expand userAccountControl    
        $_ | Add-Member -MemberType NoteProperty -Name "starts" -Value $UserStatus -PassThru

    } | export-csv added-filed.csv
Related