问题描述
我在PS中遇到了一个非常奇怪的情况.
I have come across a very strange situation in PS.
在我拥有的脚本中,有一个cmdlet(Get-Mailbox
),该cmdlet会拉回一些邮箱并将其存储在$mailboxes
中.
In a script I have, there is a cmdlet (Get-Mailbox
) which pulls back a few mailboxes and stores them in $mailboxes
.
然后我按以下步骤遍历,以找到匹配的AD帐户.
I then loop through this as follows to find a matching AD account.
foreach ($user in $mailboxes) {
Get-ADUser -Filter {UserPrincipalName -eq $user.UserPrincipalName}
}
运行此命令时,出现错误,提示它在$user
上找不到属性UserPrincipalName
.
When I run this it errors saying that it can't find the property UserPrincipalName
on $user
.
我已经调试了脚本并对其进行了彻底的测试.如果我键入$user.UserPrincipalName
会出错,它会输出UPN列表,并且它们的日期类型是字符串,因此该属性在那里并且具有数据.
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.
我得出的结论是,出于某些原因,-Filter
无法看到$user
变量-好像它被隔离在{}括号内,我听说过函数可能就是这种情况.但是,如果我像这样修改代码,它将起作用.
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?
值得注意的是,get-mailbox实际上首先连接到Exchange Online,并返回以下数据类型:
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
,但是当Get-ADUser
命令出错时,它表示该对象的类型为PSCustomobject
.我认为这可能是问题的一部分.
but when the Get-ADUser
command errors it says the the object is of type PSCustomobject
. I think this maybe part of the problem.
推荐答案
Get-ADUser -Filter "userprincipalname -eq '$($user.userprincipalname)'"
我不知道为什么,但是这里还有更多讨论,涉及哪些语法与Get-ADUser一起使用以及不起作用,以及您所使用的脚本块语法如何与完整的用户对象一起使用,而不与PSCustomObject一起使用,此处:
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
这篇关于如何将变量传递给-Filter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!