Get-ADuser脚本问题

时间:2019-02-01 18:20:37

标签: powershell

我想将CSV文件中的电子邮件地址列表与Active Directory进行比较。我在将所有部件组合在一起时遇到困难。

伪代码:

  • 将电子邮件地址列表导入对我公司的活动目录的查询中。
  • 加入电子邮件地址。
  • 仅返回在AD中启用了帐户的那些记录。

代码:

Import-Csv users.csv |
     Get-ADUser -Filter {mail -eq $_.mail } |
     where {$_.enabled -eq $true} |
     Select-Object -Property DistinguishedName, samaccountname, mail, enabled

我认为我需要为SearchBase添加其他信息,但是我不知道如何添加它。

例如:-SearchBase "DC=na,DC=corp,DC=<company name>,DC=com"

在CSV文件中是一列。列名是邮件。我要加入的AD属性是邮件。

4 个答案:

答案 0 :(得分:0)

您可以将csv导入存储在一个变量中,并获取所拥有的AD中所有电子邮件地址,在列表之间使用Compare-Object,然后对结果使用foreach。

$matchingUsers = New-Object System.Collections.ArrayList
$csv = import-csv users.csv 
$emails = $(get-aduser -filter * -Properties mail,Enabled | ? {$_.Enabled -eq $True} | select mail).mail
$comparison = $($(compare-object -ReferenceObject $a -DifferenceObject $b -IncludeEqual)| ? {$_.SideIndicator -eq '=='}).InputObject
foreach($object in $comparison) {
     $user = Get-ADUser -Filter {mail -eq $object} -SearchBase "DC=na,DC=corp,DC=,DC=com" -Properties DistinguishedName,samaccountname,mail,enabled
     $matchingUsers.Add($user)
}

然后导出$matchingUsers,将其格式化为表格,此后所需的任何内容

答案 1 :(得分:0)

要让 streamline 缩短 trebleCode的建议,您可以从以下类似内容开始:

$MailAddressList = Import-Csv -Path users.csv
$AllUsersList = Get-ADUser -Filter * -SearchBase 'DC=na,DC=corp,DC=,DC=com' -Properties DistinguishedName,samaccountname,mail,enabled | Where-Object {$_.enabled}
Compare-Object -ReferenceObject $MailAddressList -DifferenceObject $AllUsersList -Property 'Mail' -PassThru -IncludeEqual -ExcludeDifferent

如果需要,您可以将-ReferenceObject-DifferenceObject交换。我目前没有要测试的Active Directory。

答案 2 :(得分:0)

获取csv电子邮件作为字符串数组($ array)。选择-expand是您的朋友。

从AD中获取用户,通过管道传输到foreach-object,并询问$ array.Contains(通过管道传输到对象中的电子邮件地址属性)。

如何处理该条件的结果由您决定;处理它的方法很多。但是您需要一种毫不费力的方式来获取您所要的内容,这就是我所提供的。

答案 3 :(得分:0)

我可能会做这样的事情:

# enter the DistinghuishedName of the OU where the users to check are in
$SearchBase = 'DC=na,DC=corp,DC=,DC=com'
$CsvPath    = 'PATH TO THE USERS.CSV FILE'

$UserList   = Import-Csv -Path $CsvPath
# for fast lookup, best use a Hashtable
$MailLookup = @{}
foreach ($user in $UserList) {
    $MailLookup[$user.mail] = $true   # the value is not important here
}

# in fact, the properties DistinguishedName,SamAccountName and Enabled are returned by default
Get-ADUser -Filter * -SearchBase $SearchBase -Properties DistinguishedName,SamAccountName,EmailAddress,Enabled | 
     Where-Object {$_.Enabled -and $MailLookup.ContainsKey($_.EmailAddress) }

希望这会有所帮助

相关问题