Hi,
I want to count how many groups where deleted correctly and how many did not succeed,
However the output of the deleted correctly stops at 1 and the removed is always 0
what am I doing wrong?
[pre]
Connect-AzureAD
#read file with users (email address)
$users = import-csv c:\temp\toRemove.csv
$ErrorLog = "c:\temp\groupdeletionErrors.txt"
foreach ($user in $users) {
#check if the user is disabled
$accountEnabled = Get-AzureADUser -ObjectId $user.samAccountName
if(!($accountEnabled.AccountEnabled)) {
#get the users objectID from Azure
$UserObjectID =get-AzureAdUser -objectId $user.SamAccountName |select objectID
#grab the clean objectID from the user
$SelectUserObjectID= $userObjectID.objectID
#find all the groups a user is member off
$UserObjectIDGroupMemberShip = get-AzureAdUserMembership -objectID $SelectUserObjectID
$a= $userObjectIDGroupMemberShip.count
foreach ($group in $UserObjectIDGroupMemberShip) {
$Groupsremoved = 0
$ErrorGroup = 0
#remove the user from each indivudual group
try {
Remove-AzureADGroupMember -ObjectId $group.objectID -MemberId $SelectUserObjectID
$Groupsremoved++
}
catch {
#the groups that cannot be removed are safed in the error log
"Error removing $group : $($_)" |Add-content $ErrorLog
$ErrorGroup++
}
finally {
#output on screen
"$($user.SamAccountName) is removed from - $($group.DisplayName)"
}
}
write-host "Total groups Found: $a "
Write-host "Total groups Removed: $Groupsremoved"
Write-host "Total groups not removed: $Errorgroup"
}
Else {
write-host "$($user.SamAccountName) cannot be removed at this time"
}
}
[/pre]
Paul