How to pass a variable to -Filter

I came across a very strange situation in PS.

In the script, I have a cmdlet ( Get-Mailbox ) that drops several mailboxes and stores them in $mailboxes .

I then repeat this as follows to find the appropriate AD account.

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

When I run this, errors say that it cannot find the UserPrincipalName property on $user .

I debugged the script and tested it thoroughly. At the moment when it is wrong, if I type $user.UserPrincipalName , it displays the UPN list, and their date type is a string, so the property is and has data.

I came to the conclusion that, for some reason, -Filter cannot see the $user variable - as if it is isolated inside the brackets {}, which, as I heard, can take place with functions. However, if I modify the code as if it works.

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

Although this fixes my problem, I would like to know why the first example does not work. Can someone explain?

Something worth noting is that the mailbox really connects to Exchange Online first and returns the data type:

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

but when Get-ADUser it says that the object is of type PSCustomobject . I think this may be part of the problem.

0
source share
1 answer
 Get-ADUser -Filter "userprincipalname -eq '$($user.userprincipalname)'" 

I don’t know why, but there are some more discussions about what syntaxes do and don’t work with Get-ADUser, and how the syntax of the script block that you use works with a full user object, but not with PSCustomObject, here:

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

+2
source

Source: https://habr.com/ru/post/1202977/


All Articles