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.