PowerShell Tip: Passing A Variable In PowerShell That Contains An Apostrophe
PowerShell Tip: Passing A Variable In PowerShell That Contains An Apostrophe
Summary
This Technet Wiki is based on TechNet Form Post
Issue
Unable to query AD user with Apostrophe.
Error
No Apostrophe
PS C:\ $PersonOnLeaveValue = "General User"
PS C:\ $PersonOnLeaveUsername = (Get-ADUser -Filter "Name -like '$PersonOnLeaveValue'" -Properties *).samAccountName
PS C:\ echo $PersonOnLeaveUsername generalu
With An Apostrophe
PS C:\ $PersonOnLeaveValue = "FirstName O'LastName"
PS C:\ $PersonOnLeaveUsername = (Get-ADUser -Filter "Name -like '$PersonOnLeaveValue'" -Properties *).samAccountName
Get-ADUser : Error parsing query: 'Name -like 'FirstName O'LastName'' Error Message: 'syntax error' at position: '24'. At line:1 char:27 + $PersonOnLeaveUsername = (Get-ADUser -Filter "Name -like '$PersonOnLeaveValue'" ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ParserError: (:) [Get-ADUser], ADFilterParsingException + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADFilterParsingException,Microsoft.ActiveDirectory.Management.Commands.GetADUser
Solution
We need to use Quotes and Back tick accordingly to avoid the above error
$readvalue = "William O'Brian" #Method 1 (Get-ADUser -Filter {Name -eq $readvalue} -Properties *).SamaccountName #Method 2 (Get-ADUser -Filter "Name -eq `$readValue" -Properties *).SamaccountName |