How to pass a variable to -Filter

2020-05-03 13:03发布

问题:

I have come across a very strange situation in PS.

In a script I have, there is a cmdlet (Get-Mailbox) which pulls back a few mailboxes and stores them in $mailboxes.

I then loop through this as follows to find a matching AD account.

foreach ($user in $mailboxes) {
    Get-ADUser -Filter {UserPrincipalName -eq $user.UserPrincipalName}
}

When I run this it errors saying that it can't find the property UserPrincipalName on $user.

I have debugged the script and tested it thoroughly. At the point where it errors if I type $user.UserPrincipalName it outputs a list of UPNs and their date type is string so the property is there and has data.

I came to the conclusion that for some reason -Filter can't see the $user variable - as if it is isolated inside the {} brackets which I have heard can be the case with functions. However if I modify the code like so it works.

foreach ($user in $mailboxes) {
    $name = $user.UserPrincipalName
    Get-ADUser -Filter {UserPrincipalName -eq $name}
}

Although this fixes my problem I'd like to learn why the first example doesn't work. Can anyone explain?

Something worth noting is the get-mailbox actually connects to Exchange Online first and returns a data type of:

Deserialized.Microsoft.Exchange.Data.Directory.Management.Mailbox

but when the Get-ADUser command errors it says the the object is of type PSCustomobject. I think this maybe part of the problem.

回答1:

Get-ADUser -Filter "userprincipalname -eq '$($user.userprincipalname)'"

I don't know why, but there's some more discussion here about which syntaxes do and don't work with Get-ADUser, and how the scriptblock syntax you are using works with a full user object but not with a PSCustomObject, here:

http://www.powershellish.com/blog/2015-11-17-ad-filter