[英]Adding multiple users to multiple Teams through Powershell using .csv
[英]Remove multiple users from multiple Teams if NOT in csv
我有一個腳本,可將用戶從 a.csv 添加到 Teams,但在創建后的前幾周可能需要考慮添加/刪除。
# 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
}
}
}
目前,我可以通過將用戶信息添加到.csv 來將用戶添加到團隊,但如果在文件中找不到用戶,我希望能夠刪除用戶。 我在另一個答案中發現了這個選擇:
$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
我不確定包含此內容的最佳方式。 在我當前的腳本中,我可以從填充的團隊中檢查和刪除 a.csv 中未找到的用戶?
請你試試下面的邏輯:
[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
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.