在Powershell中比较2个列表

我不是超级专家,所以请多加注意。 我有一个来自sql的电子邮件地址列表: $NotEnroled = Invoke-Sqlcmd -ServerInstance "my-server" -Database "my-db" -Query "select username from StudentsToDeleteFromO365"

我也有来自o365交换的所有邮箱的列表:

$Mailboxes = get-mailbox -resultsize unlimited | where {($_.UserPrincipalName -match '@students.test.com') -and (($_.ForwardingSmtpAddress -ne $NULL) -or ($_.ForwardingAddress -ne $NULL))} | Select UserPrincipalName

我在尝试仅获取$ NotEnrolled中存在的$ mailboxs列表时遇到了困难,因此我以后可以删除许可证并删除o365帐户。

imauzhw 回答:在Powershell中比较2个列表

正如AdminOfThings所评论的那样,您用于检索$Mailboxes变量的代码为您提供了一个对象数组,每个对象都有一个属性'UserPrincipalName'。

由于您要与另一个包含字符串的数组进行比较,因此将无法正常工作。

此外,您还需要使用正则表达式-match运算符测试字符串'@students.test.com',但是在正则表达式中,点具有特殊含义(任何字符),因此您需要使用反斜杠对这些点进行转义。 / p>

这应该对您有用:

# Get a string array of users to be deleted from the database
$NotEnroled = Invoke-Sqlcmd -ServerInstance "my-server" -Database "my-db" -Query "select UserName from StudentsToDeleteFromO365"

# Get a string array of UserPrincipalNames.
# Because of using the regex '-match' operator,you need to escape the dots in the string.
# The '$' anchors the regex to match from the end of the string.
$Mailboxes = Get-Mailbox -ResultSize Unlimited | 
             Where-Object {($_.UserPrincipalName -match '@students\.test\.com$') -and 
                          (($null -ne $_.ForwardingSmtpAddress) -or ($null -ne $_.ForwardingAddress))} | 
             Select-Object -ExpandProperty UserPrincipalName

# Next find the items in the $Mailboxes array that exist in $NotEnrolled
$UsersToDelete = @($Mailboxes | Where-Object { $NotEnroled -contains $_ })

变量$UsersToDelete现在具有$Mailboxes数组中所有$NotEnroled数组中的UPN。

本文链接:https://www.f2er.com/3167371.html

大家都在问