Remove multiple users from multiple Teams if NOT in csv

Viewed 50

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?

1 Answers

Can you please try the below logic:

[array]$teams = "T1","T2","T3"
$users = gc C:\temp\UserList.txt

foreach ($user in $users) {
    $user = ($user -split "@")[0] # SamAccountName from UPN
    foreach($t in $teams) {
        $tMems = Get-AdGroupMember $t |select -exp SamAccountName
        if ($tMems -match $user) {
            RemoveAdGroupMember $t $user
        }
    }
}
Related