$alladusers = Get-ADUser -Filter * | Select sAMAccountName
如果您正在处理的域很大,这不是一个好主意。使用Where-Object
过滤大对象也不是一个好主意,powershell.org 上有一篇非常酷的文章,其中 Dave Wyatt 和 Don Jones 解释了过滤对象的不同方法及其效率,遗憾的是由于某种原因它被删除了。
我会做这样的事情,假设您的 Csv 对每个用户都有一个“用户”列:
$result=New-Object System.Collections.ArrayList
#result array will be only the user that do not exist in AD
$csvfile = Import-CSV USERAccountstocompare.csv
foreach($line in $csvfile.User)
{
$filter="(|(Name=$line)(samAccountName=$line))"
$adusr=Get-ADuser -LDAPFilter $filter
if(!$adusr)
{
$result.add($line) > $null
}
}
相反,如果您想要一个包含在 Csv 和 AD 上的用户以及仅在 Csv 中的用户的列表,您可以执行以下操作:
$result=New-Object System.Collections.ArrayList
#result array will be only the user that do not exist in AD
$csvfile = Import-CSV USERAccountstocompare.csv
foreach($line in $csvfile.User)
{
$filter="(|(Name=$line)(samAccountName=$line))"
$adusr=Get-ADuser -LDAPFilter $filter
if(!$adusr)
{
$result.add(
[pscustomobject]@{
'Not In AD'=$line
}) > $null
}
else
{
$result.add(
[pscustomobject]@{
'In AD and Csv'=$line
}) > $null
}
}