Forum Discussion
Powershell help with AD Groups
Could someone help with the if, if, elseif statement below?
This is what I'm trying to accomplish.
1. if the group is empty move it to target OU.
2. if the group is non-empty and is a Distribution group, remove all members then move it to target OU.
3. if the group is non-empty and is a Security group, convert it to a Distribution group then move it to target OU.
foreach ($Group in $Groups) {
$Groups | Get-ADGroup -Properties Member,GroupCategory | Select-Object member,groupcategory
## Move all Distribution or Security Groups that are empty to new OU.
if ($_.members.count -eq 0){
Get-ADGroup -Identity $Group | Move-ADObject -TargetPath $TargetOU
Write-Host "$Group is empty!" -ForegroundColor green
}
## Remove members from non-empty Distribution groups and move the group to new OU.
if ($_.members.count -ne 0 -and $_.GroupCategory -eq 'Distribution'){
{
Remove-ADGroupMember -Identity $Group -Members (Get-ADGroupMember -Identity $Group) -Confirm:$False | Move-ADObject -TargetPath $TargetOU
## Convert non-empty Distribution groups to Security group and move the group to new OU.
elseif ($_.members.count -ne 0 -and $_.GroupCategory -eq 'Security'){
{
Get-ADGroup -Identity $Group | Set-ADGroup -GroupCategory Distribution
Get-ADGroup -Identity $Group | Move-ADObject -TargetPath $TargetOU
}
}
}
Be careful with your { use, also indent your code it helps with picking the that {} are in the right place. Also because you are using a foreach loop you do not need to pipe $Groups to Get-ADGroup each time, you only need to do it for group you are currently working with
foreach ($Group in $Groups) {
Get-ADGroup -Identity $Group -Properties Member,GroupCategory | Select-Object member,groupcategory
## Move all Distribution or Security Groups that are empty to new OU.
if ($_.members.count -eq 0){
Get-ADGroup -Identity $Group | Move-ADObject -TargetPath $TargetOU
Write-Host "$Group is empty!" -ForegroundColor green
}
## Remove members from non-empty Distribution groups and move the group to new OU.
if ($_.members.count -ne 0 -and $_.GroupCategory -eq 'Distribution'){
Remove-ADGroupMember -Identity $Group -Members (Get-ADGroupMember -Identity $Group) -Confirm:$False | Move-ADObject -TargetPath $TargetOU
}
## Convert non-empty Distribution groups to Security group and move the group to new OU.
elseif ($_.members.count -ne 0 -and $_.GroupCategory -eq 'Security'){
Get-ADGroup -Identity $Group | Set-ADGroup -GroupCategory Distribution
Get-ADGroup -Identity $Group | Move-ADObject -TargetPath $TargetOU
}
}
You could however have the