Created
June 28, 2024 07:28
-
-
Save YuukiNishikido/a22b6e80bdcf8502fa9b11508f48695a to your computer and use it in GitHub Desktop.
読み込んだCSVの値に応じてADユーザーのセキュリティグループを一括で変更するPowerShell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 読み込むCSVのパスをセット | |
| $csvPath = "C:\ADユーザー編集ツール\人事異動処理用\source.csv" | |
| #処理時点の日時を取得 | |
| $astdate = Get-Date -format "yyyyMMddHHmm" | |
| #処理できなかったデータを記録するログのパスをセット | |
| $logPath = "C:\ADユーザー編集ツール\人事異動処理用\$($astdate)_エラーログ.txt" | |
| # CSVファイルをUTF-8にエンコード(UTF-8にしないと日本語が文字化けする) | |
| (Get-Content -Path $csvPath -Encoding default) | Set-content -Path $csvPath -Encoding UTF8 | |
| # CSVファイルからデータを取り込み | |
| $users = Import-Csv -Path $csvPath | |
| # CSVファイルのデータ件数分繰り返す | |
| # 職員番号でユーザーを特定し、新しい部署のセキュリティグループへの変更とフォルダ割り当てのスクリプトを変更する処理 | |
| foreach ($userdata in $users) { | |
| $userid = $userdata.memo | |
| $user = Get-ADUser -Filter {info -eq $userid} | |
| # ユーザーを特定できた場合、必要な処理を行う | |
| if($user){ | |
| # ログオンスクリプト変更 | |
| Set-ADuser -Identity $user -ScriptPath $userdata.script | |
| # セキュリティグループ変更 | |
| # Domain Users以外の権限を削除 | |
| $domainUsersGroup = "Domain Users" | |
| $userGroups = Get-ADprincipalGroupMembership -Identity $user | Where-Object { $_.Name -ne $domainUsersGroup} | |
| foreach ($group in $userGroups){ | |
| Remove-ADGroupMember -Identity $group -Members $user -Confirm:$false | |
| } | |
| # セキュリティグループをセット | |
| $groupColumns = "group1","group2","group3","group4","group5" | |
| foreach ($groupColumn in $groupColumns) { | |
| $groupName = $userdata.$groupColumn | |
| if (-not [string]::IsNullOrWhiteSpace($groupName)) { | |
| Add-ADGroupMember -Identity $groupName -Members $user.SamAccountName | |
| } | |
| } | |
| # ユーザー特定できなかったら、ログに対象データを書き出す | |
| } else { | |
| $logMessage = "職員番号:$($userid)のアカウントが見つかりませんでした。状況を確認し、個別に対処を行ってください。" | |
| Add-Content -Path $logPath -Value $logmessage | |
| Add-Content -Path $logPath -Value "`n" #空行を追加 | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment