I'm cycling through a list of users and need to call get-azureaduser
with each one.
The email address is stored in a variable $email
and my command looks like this:
$user = Get-AzureAdUser -filter "mail eq '$email'"
This works fine for most users but not for those with an apostrophe in their name.
If there is an apostrophe it throws an error:
Message: Unsupported or invalid query filter clause specified for property 'mail' of resource 'User'.
I've tried various things for the filter parameter (e.g. surrounding in "" etc) but none of these worked.
The way to escape a single quote '
in an OData filter is by doubling down on it, an efficient way to handle this when the value being fed to the filter could have single quotes in it can be with the .Replace
method. Additionally, Microsoft has a section on how to handle escaping of quotes, for queries to the Graph API (the same solution also applies to the old API used by the AzureAD Module). See Escaping single quotes.
$email = $email.Replace("'", "''")
$user = Get-AzureAdUser -Filter "mail eq '$email'"
As aside, consider migrating your code to the Microsoft.Graph Module, the AzureAD Module is deprecated and the API it's calling behind the scenes will no longer work in the future. See Important: Azure AD Graph Retirement and Powershell Module Deprecation for more information.
You can use Get-MgUser
as a replacement in this case, the code would look pretty similar:
$email = $email.Replace("'", "''")
$user = Get-MgUser -Filter "mail eq '$email'"