简体   繁体   中英

Powershell escaping single quotes

How can I escape the single quote in the below Powershell command?

Get-Recipient -Filter "Members -eq 'CN=Jane D'Amico (Contoso),OU=fourthcoffee.onmicrosoft.com,OU=Microsoft Exchange Hosted Organizations,DC=NAMPR1AA001,DC=PROD,DC=OUTLOOK,DC=COM'"

I suspect this is failing due to the D'Amico . Not a powershell person so please go easy on me.

Cannot bind parameter 'Filter' to the target. Exception setting "Filter": "Invalid filter syntax.

As long as you're just passing a string (which you are), you can use doublequotes again, and escape it like so:

Get-Recipient -Filter "Members -eq `"CN=Jane D'Amico (Contoso),OU=fourthcoffee.onmicrosoft.com,OU=Microsoft Exchange Hosted Organizations,DC=NAMPR1AA001,DC=PROD,DC=OUTLOOK,DC=COM`""

To escape quotes you need to double them up, so D'Amico needs to become D''Amico.

A good way to handle this would be to assign your user string to a variable first

$user = "CN=Jane D'Amico (Contoso),OU=fourthcoffee.onmicrosoft.com,OU=Microsoft Exchange Hosted Organizations,DC=NAMPR1AA001,DC=PROD,DC=OUTLOOK,DC=COM"

then replace any single quotes inside before using it

$user = $user -replace "'", "''"    
Get-Recipient -Filter "Members -eq '$user'"

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