Powershell Get-AdObejct with -filter option containing variable

WurthAdmin
WurthAdmin used Ask the Experts™
on
Hi,
When i execute this powershell command line i have some result :
Get-ADObject -Properties mail, proxyAddresses -Filter {mail -like "*pierre.w*" -or proxyAddresses -like "*pierre.w*"} |ft

but when i execute those lines i've got a error :
$emailportion="pierre.w"
$filtre="{mail -like ""*$emailportion*"" -or proxyAddresses -like ""*$emailportion*""}"
Get-ADObject -Properties mail, proxyAddresses -Filter $filtre

Get-ADObject : Error parsing query: '{mail -like "*pierre.w*" -or proxyAddresses -like "*pierre.w*"}' Error Message: 'syntax error' at position: '1'.
At line:1 char:1
+ Get-ADObject -Properties mail, proxyAddresses -Filter $filtre
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ParserError: (:) [Get-ADObject], ADFilterParsingException
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADFilterParsingException,Microsoft.ActiveDirectory.Management.Commands.GetADObject

The variable $filtre contain : {mail -like "*pierre.w*" -or proxyAddresses -like "*pierre.w*"}

The help on get-ADObject show the -filter option as a string
SYNTAX
    Get-ADObject [-AuthType {Negotiate | Basic}] [-Credential <PSCredential>] [-IncludeDeletedObjects] [-Properties <String[]>] [-ResultPageSize <Int32>] [-ResultSetSize <Int32>] [-SearchBase <String>]
    [-SearchScope {Base | OneLevel | Subtree}] [-Server <String>] -Filter <String> [<CommonParameters>]
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2018
Distinguished Expert 2018
Commented:
Try it like this:
$emailportion="pierre.w"
$filtre = "(mail -like '*$emailportion*') -or (proxyAddresses -like '*$emailportion*')"
Get-ADObject -Properties mail, proxyAddresses -Filter $filtre

Open in new window

Author

Commented:
Thank you it works well.

Best Regard
JP

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial