I have a script which adds users to Teams from a .csv, but there are likely to be additions/removals which will need to be accounted for in the first weeks after creation.
# Read team users from CSV file
$TeamUsers = Import-CSV "File_Path"
$i = 0
# Group the objects by their TeamDesc property, so we only query each group once
$TeamUsers | Group-Object TeamDesc | ForEach-Object {
# Get the GroupId of this Group
$groupId = (Get-Team -DisplayName $_.Name).GroupId
# If the Group couldn't be found, just skip below logic
if(-not $groupId) { return }
# If the Group could be found, create a hashtable for future splatting
$params = @{ GroupId = $groupId }
# now we can enumerate each object in each group of objects
foreach($user in $_.Group) {
try {
# create a hashtable for splatting progress
$progress = @{
PercentComplete = $i++ / $TeamUsers.Count * 100
Activity = 'Adding Users to MS Teams!!'
Status = 'Working on Team: "{0}" and User: "{1}"' -f $_.Name, $user.UserPrincipleName
}
Write-Progress @progress
# add this user with this role to the hashtable
$params['User'] = $user.UserPrincipleName
$params['Role'] = $user.Role
Add-TeamUser @params
}
catch {
('Error occurred for {0} - {1}' -f $user.TeamName, $user.UserPrincipleName),
$_.ToString() | Write-Warning
}
}
}
Currently, I can add users to the Team by adding their user information to the .csv but I want to be able to remove users if they are not found in the file. I found, in another answer, this selection:
$validUsers = Import-Csv 'C:\path\to\your.csv' | Select-Object -Expand dn
$invalidUsers = Get-ADGroupMember 'groupname' |
Where-Object { $validUsers -notcontains $_.distinguishedName }
Remove-ADGroupMember 'groupname' $invalidUsers -WhatIf
I am unsure of the best way to include this. Where in my current script can I incorporate checking for and removing users NOT found in a .csv from the populated Teams?