How about something like this?
This has NOT been tested!
$i = 0
$EmployeeGroupName = 'employees'
$StudentGroupName = 'students'
$EmployeeGroupDN = (Get-ADGroup $EmployeeGroupName).distinguishedName
$StudentGroupDN = (Get-ADGroup $StudentGroupName).distinguishedName
$h = @{
# group database policy
$EmployeeGroupName = 'staff-db', 'staff Policy'
$StudentGroupName = 'student-db', 'student Policy'
}
Get-ADUser -Filter * -Properties objectCategory, memberOf |
Where-Object { $_.objectCategory -like "CN=Person,*" } |
ForEach-Object {
$i++
$db = ""
$pol = ""
$add = $false
if ($_.memberOf -contains $EmployeeGroupDN -AND $_.memberOf -contains $StudentGroupDN) {
# this is probably an error. can a user belong to both groups?
Write-Host "$($_.samaccountname) is in both groups!"
}
elseif ($_.memberOf -contains $EmployeeGroupDN) {
$db = $h.$EmployeeGroupName[0]
$pol = $h.$EmployeeGroupName[1]
$add = $true
}
elseif ($_.memberof -contains $StudentGroupDN) {
$db = $h.$StudentGroupName[0]
$pol = $h.$StudentGroupName[1]
$add = $true
}
else {
# user is not a member of either group. if this an error?
Write-Host "$($_.samaccountname) isn't a member of either group"
}
if ($add) {
$alias = ($_.userprincipalname -split '@')[0]
# Output the alias to the screen:
Write-Host $alias
# Enable the exchange mailbox
Enable-Mailbox -Identity $_.userprincipalname -Alias $alias -Database $db -RetentionPolicy $pol
}
}
"Total $i"
Edit: Changed -Filter. Added objectCategory to -Properties. Added "Where-Object". Added place-holder error messages