どうもミツシマです。

今回はMicrosoft365(旧名称 Office365)の管理者情報を一括で取得するコマンドを検証してみました。
いつの間にか名称が変更されてるんですよね。。。(汗)


↓↓いつも通り完成したスクリプトがこちら↓↓

〜Get-M365Administrators.ps1〜

#環境変数
$CurrentFolder = Split-Path $MyInvocation.MyCommand.Path -Parent
$LogFile = $CurrentFolder + "\管理者情報.csv"

#MSOへ接続
$UserCredential = Get-Credential
try{
Connect-MsolService -Credential $UserCredential -ErrorAction Stop
}catch{
#接続でエラー発生の際に処理中断
Write-Host "MSOへの接続に失敗しました.IDとPWを再確認してください.`r`n" -ForegroundColor Red
    Write-Host "処理を中断します.`r`n" -ForegroundColor Red
    pause
    Exit
}

#接続(リモートセッションの作成)
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection

#接続(リモートセッションの作成) プロキシ環境の場合
#$proxyOptions = New-PSSessionOption -ProxyAccessType IEConfig -ProxyAuthentication Negotiate
#$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection -SessionOption $proxyOptions


Write-Host "`r`n"
Write-Host "MSOへ接続成功しました.各種情報取得を実行します.`r`n" -ForegroundColor Yellow
Write-Host "処理が完了するまで、そのままでお待ちください.`r`n" -ForegroundColor Yellow

#管理者情報取得
$AllRole = Get-MsolRole
$Array = @()
$ht = @{ObjectId=""; Name=""; RoleMemberType=""; DisplayName=""; EmailAddress=""; isLicensed=""}
$i = 0
foreach($Role in $AllRole){
    $RoleMember = Get-MsolRoleMember -RoleObjectId $Role.ObjectId

    If (-Not([String]::IsNullOrEmpty($RoleMember))){

        foreach($RMember in $RoleMember){
            $Array += New-Object psobject -Property $ht
            $Array[$i].ObjectId = $Role.ObjectId
            $Array[$i].Name = $Role.Name
            $Array[$i].RoleMemberType = $RMember.RoleMemberType
            $Array[$i].DisplayName = $RMember.DisplayName
            $Array[$i].EmailAddress = $RMember.EmailAddress
            $Array[$i].isLicensed = $RMember.isLicensed
            $i = $i + 1
        }
    }
}

$Array = $Array | Select-Object ObjectId,Name,RoleMemberType,DisplayName,EmailAddress,isLicensed

#CSVへ出力
$Array | Export-Csv -Path $LogFile -Encoding Default -NoTypeInformation

Write-Host "処理が完了しました.各種情報がCSVファイルに出力されました.`r`n"  -ForegroundColor Yellow

pause


〜解説〜

基本的には「Get-MsolRole」・「Get-MsolRoleMember」を使用しています。
管理者ロールが割り当てられているユーザー一覧を取得し、それぞれのメンバーの情報を適宜出力している感じとなります。
いつも思うことなのですが、MSOlineモジュールのコマンドは引数としてオブジェクトIDを必要とすることが多い気がします(汗)

そんな感じで最終的にハッシュテーブルに「(管理ロール)オブジェクトID」・「(管理ロール)名称」・「(管理ロール)メンバータイプ」・「(管理ロール)メンバーの表示名」・「(管理ロール)メンバーのメールアドレス」・「(管理ロール)メンバーのライセンス付与状況」を出力しています。
※「Select-Object」を使用ているのは「種別」の順番を揃える為の念の為の処理です。

そして最後にスクリプトが配置されているフォルダと同じ場所に「管理者情報.csv」を出力する形である。


↓↓実行するとこんな感じになります↓↓
コマンド実行画面

↓↓出力されたCSVファイルのイメージです↓↓
CSVファイル画面


こんな感じで今回の検証は終了です。

管理者ロールが割り当てられているユーザーをGUI(Microsoft365管理センター)から確認しようとすると中々大変だと思われますので、参考になれば幸いです♪
スポンサードリンク