📝

Active Directory:ユーザーの所属グループをCSV出力

に公開

オンプレAD環境でユーザーのアクセス権を整理するために所属グループをCSV出力するPowerShellを書いてみた。

前提条件

  • ドメインコントローラーにコンソールかリモートデスクトップでログオンして操作する
  • 管理者の PC から操作する場合は、Active Directory モジュールが使えること

処理の中身

  • ユーザーの所属グループを5つまでCSV出力(アカウント名,所属グループ1,2,3,4,5)
Member_Separated.csv
"SamAccountName","GroupCount","Group1","Group2","Group3","Group4","Group5"
"test-user01","5","sec-member01","sec-member02","sec-member03","sec-member04","sec-member05"
"test-user02","2","sec-member01","sec-member02","","",""
  • MemberOf1,SamAccountNameで並び替え
  • Shift_JISでCSV出力

完成したスクリプト

GetAllUserMember.ps1
<#
.SYNOPSIS
    指定したOU配下のユーザー情報を抽出し、所属グループ(最大5つ)を列ごとに分割してCSVに出力する。
    ※監査用フェイルセーフとして所属グループ総数(GroupCount)を付与。
#>
param (
    [Parameter(Mandatory=$false)]
    [string]$TargetOU = "OU=〇〇,DC=〇〇,DC=〇〇",

    [Parameter(Mandatory=$false)]
    [string]$OutFile = "Member_Separated.csv"
)

$ErrorActionPreference = "Stop"

try {
    Write-Host "処理を開始します。対象OU: $TargetOU" -ForegroundColor Cyan

    if (-not (Get-Module -Name ActiveDirectory -ListAvailable)) {
        throw "ActiveDirectoryモジュールが存在しません。"
    }
    Import-Module ActiveDirectory

    $users = Get-ADUser -Filter * -SearchBase $TargetOU -SearchScope Subtree -Properties MemberOf

    if ($users.Count -eq 0 -or $null -eq $users) {
        Write-Warning "指定されたOU配下にユーザーが存在しません。"
        exit
    }

    # オブジェクトの加工とCSV出力
    $users | Select-Object SamAccountName,
        # 監査用のフェイルセーフ:所属しているグループの総数を出力
        @{Name="GroupCount"; Expression={ if ($_.MemberOf) { $_.MemberOf.Count } else { 0 } }},
        
        # 配列のインデックスエラーを回避しつつ、正規表現でCNのみを抽出
        @{Name="Group1"; Expression={
            $groups = @($_.MemberOf)
            if ($groups.Count -gt 0 -and $groups[0] -match "^CN=(.*?),") { $matches[1] }
        }},
        @{Name="Group2"; Expression={
            $groups = @($_.MemberOf)
            if ($groups.Count -gt 1 -and $groups[1] -match "^CN=(.*?),") { $matches[1] }
        }},
        @{Name="Group3"; Expression={
            $groups = @($_.MemberOf)
            if ($groups.Count -gt 1 -and $groups[2] -match "^CN=(.*?),") { $matches[1] }
        }},
        @{Name="Group4"; Expression={
            $groups = @($_.MemberOf)
            if ($groups.Count -gt 1 -and $groups[3] -match "^CN=(.*?),") { $matches[1] }
        }},
        @{Name="Group5"; Expression={
            $groups = @($_.MemberOf)
            if ($groups.Count -gt 2 -and $groups[4] -match "^CN=(.*?),") { $matches[1] }
        }} |
    # グループ1とSamAccountNameでソートしてから出力
    Sort-Object -Property Group1,SamAccountName |
    Export-Csv -Path $OutFile -Encoding UTF8 -NoTypeInformation -Force

    Write-Host "正常に完了しました。出力先: $($pwd)\$OutFile" -ForegroundColor Green

} catch {
    Write-Error "【エラー発生】処理中に問題が発生しました。`n詳細: $($_.Exception.Message)"
} finally {
    $ErrorActionPreference = "Continue"
}

参考

https://docs.microsoft.com/en-us/powershell/module/addsadministration/get-aduser?view=windowsserver2019-ps

関連スクリプト

https://zenn.dev/8chikuwa3/articles/9d4d23db5117ca

Discussion