I'm still working on learning powershell. I need to pull email and manager email from AD accounts in a group but exclude any records that have manager blank or email blank. I don't think I can 'where' for two where conditions, so I can get one or the other.
Get-ADGroupMember -Identity "groupname" -Recursive | Get-ADUser -properties * | where manager -NE $null | select displayname, EmailAddress, @{Name="ManagerEmail";Expression={(Get-ADUser -property Emailaddress $_.manager).emailaddress}} | export-csv -path c:\data.csv -NoTypeInformation
How would I go about getting both filtered out?
CodePudding user response:
You can use and should use the Active Directory Filter or LDAP Filter for this instead of doing the filtering with powershell:
$group = (Get-ADGroup groupname).DistinguishedName
$managerMap = @{}
$params = @{
LDAPFilter = "(&(memberof:1.2.840.113556.1.4.1941:=$group)(mail=*)(manager=*))"
Properties = 'mail', 'manager'
}
Get-ADUser @params | ForEach-Object {
if(-not $managerMap.ContainsKey($_.manager)) {
$managerMap[$_.manager] = (Get-ADUser $_.manager -Properties mail).mail
}
[pscustomobject]@{
DisplayName = $_.DisplayName
EmailAddress = $_.mail
ManagerEmail = $managerMap[$_.manager]
}
} | Export-Csv 'c:\data.csv' -NoTypeInformation
Details of the LDAP Filter:
(& # AND, all conditions must be met
(memberof:1.2.840.113556.1.4.1941:=$group) # user is a member of `$group` (recursively)
(mail=*) # mail attribute is not null
(manager=*) # manager attribute is not null
) # closing AND