Tình huống:
User mới, tạo từ app nên đã được cho sẵn vào các OU, cần add group tương ứng OU cho user.
Xử lý:
- Tạo 1 file csv mapping các OU với AD Group cần thiết: "C:\bat\OU_List.csv". Export toàn bộ các OU bằng script:
Import-Module ActiveDirectory
$output = "C:\bat\OU_List.csv"
$ous = Get-ADOrganizationalUnit -Filter * | Select-Object Name, DistinguishedName
$ous | Export-Csv -Path $output -NoTypeInformation -Encoding UTF8
Write-Host "Exported to: $output"
- Tạo thủ công file csv chứa các username mới, tên cột SamAccountName: "C:\bat\UsersToAddGroup.csv"
Chạy script powershell:
Import-Module ActiveDirectory
$ouMappingFile = "C:\bat\OU_List.csv"
$userFile = "C:\bat\UsersToAddGroup.csv"
$logFile = "C:\bat\Add_User_By_OU.log"
Start-Transcript -Path $logFile -Append
Write-Host "=== START PROCESS ==="
Write-Host ""
$ouMappings = Import-Csv $ouMappingFile
$usersToProcess = Import-Csv $userFile
$groupMembersCache = @{}
foreach ($u in $usersToProcess) {
$username = $u.SamAccountName
if ([string]::IsNullOrWhiteSpace($username)) {
continue
}
Write-Host "Processing user: $username"
$user = Get-ADUser -Identity $username -Properties DistinguishedName -ErrorAction SilentlyContinue
if (!$user) {
Write-Warning " Username does not exist"
continue
}
$userDN = $user.DistinguishedName
$matched = $false
foreach ($map in $ouMappings) {
$ouDN = $map.DistinguishedName
$groupName = $map.ADGroup
if ([string]::IsNullOrWhiteSpace($groupName)) {
continue
}
if ($userDN -like "*$ouDN") {
Write-Host " Match OU -> Group: $groupName"
$group = Get-ADGroup -Identity $groupName -ErrorAction SilentlyContinue
if (!$group) {
Write-Warning " Group does not exist: $groupName"
continue
}
if (-not $groupMembersCache.ContainsKey($groupName)) {
$groupMembersCache[$groupName] =
Get-ADGroupMember $group |
Where-Object {$_.objectClass -eq 'user'} |
Select-Object -ExpandProperty SamAccountName
}
if ($groupMembersCache[$groupName] -contains $username) {
Write-Host " [OK] Username already in group"
} else {
Add-ADGroupMember -Identity $group -Members $user
Write-Host " [ADD] Username added to $groupName"
$groupMembersCache[$groupName] += $username
}
$matched = $true
break
}
}
if (-not $matched) {
Write-Warning " Can''t find avaiale OU in mapping"
}
Write-Host ""
}
Write-Host "=== DONE ==="
Stop-Transcript
No comments:
Post a Comment