見出し画像

M365の配布グループの表示名をPowerShellで一括変更(準備編)

Microsoft365(M365)の運用において、配布グループを作成した段階では表示名に問題はなくても、配布グループの数が増えたり組織の在り方が変わったりして、表示名を再検討することがあります。

また、アカウント作成を複数人が担当していると、微妙な表記揺れが発生してしまうことも。業務上致命的な問題ではなくても、やっぱりきれいに揃えておきたいものです。

そんなときはPowerShellを使って表示名をまとめて変更してしまいましょう。

なお、Outlookでの検索は部分一致ではなく前方一致となるため、表示名の先頭には検索に使われそうな文字を入れると検索しやすくなります。

PowerShell

※ 必要なモジュールは適宜インストールしてください。

# スクリプトファイルがある場所のパスを取得
$CurrentFolder = Split-Path $MyInvocation.MyCommand.Path -Parent

# 「99_バックアップデータ」がなければ作成
if (-not(Test-Path $CurrentFolder"\99_バックアップデータ")){
    New-Item $CurrentFolder"\99_バックアップデータ" -ItemType Directory
}

# 前回のデータがあればバックアップに移動
if (Test-Path $CurrentFolder"\配布G名変更_*.xlsx"){
    Move-Item $CurrentFolder"\配布G名変更_*.xlsx" $CurrentFolder"\99_バックアップデータ"
}
if (Test-Path $CurrentFolder"\配布G名変更_Log_*.txt"){
    Move-Item $CurrentFolder"\配布G名変更_Log_*.txt" $CurrentFolder"\99_バックアップデータ"
}

# Excelを操作する為の宣言
$excel = New-Object -ComObject Excel.Application
# 起動したExcelを表示しない
$excel.Visible = $False
# ワークブックを作成
$book = $excel.Workbooks.Add()
# ワークシートを番号で指定し、接続する
$sheet = $excel.Worksheets.Item(1)

# 指定したセルに文字列を入力し、装飾する
$sheet.Cells.Item(1, 1) = "※DisplayNameを変更するとNameも同時に変更されます。"
$sheet.Cells.Item(1, 1).font.color = 0x0000ff
$sheet.Cells.Item(2, 1) = "[Before]Displayname"
$sheet.Cells.Item(2, 2) = "[After]Displayname"
$sheet.Cells.Item(2, 4) = "RecipientTypeDetails"
$sheet.Cells.Item(2, 5) = "Name"
$sheet.Cells.Item(2, 6) = "EmailAddresses"
$sheet.range("A2:A2").interior.color = 0xC0C0C0
$sheet.range("B2:B2").interior.color = 0x666666
$sheet.range("D2:F2").interior.color = 0xC0C0C0
$sheet.range("B2:B2").font.color = 0xffffff
$sheet.range("A2:F2").HorizontalAlignment = -4108

# 列幅を自動調整する
$sheet.Range("A1:F1").columnwidth = 30
$sheet.Columns.item(3).columnwidth = 2

# 認証情報を入力
$Credential = Get-Credential

# ExchangeOnlineに接続
Connect-ExchangeOnline -Credential $credential
$AllDistributionGroup = Get-DistributionGroup -ResultSize Unlimited | 
    Select-Object DisplayName, Name, EmailAddresses, RecipientTypeDetails

$total = $AllDistributionGroup.count
# 最新情報を入力
for ($i = 0; $i -lt $total; $i++) {
    $sheet.Cells.Item($i+3, 1).value = [string]$AllDistributionGroup[$i].DisplayName
    $sheet.Cells.Item($i+3, 4).value = [string]$AllDistributionGroup[$i].RecipientTypeDetails
    $sheet.Cells.Item($i+3, 5).value = [string]$AllDistributionGroup[$i].Name
    $sheet.Cells.Item($i+3, 6).value = [string]$AllDistributionGroup[$i].EmailAddresses
    $per = $i / $total * 100
    Write-Progress -activity "書き込み中" -status $i"/"$total -percentComplete $per
}
# 名前をつけて保存
$book.SaveAs("$CurrentFolder\配布G名変更_$(Get-Date -Format "yyyyMMdd_HHmmss").xlsx")
# Excelを閉じる
$excel.Quit()
# プロセスを解放する
$excel = $null
[GC]::Collect()

# 接続を切断
Disconnect-ExchangeOnline -Confirm:$false

※ 本コードを利用する場合は必ず以下の免責事項をご確認ください。

おわり

準備編は以上です。更新編は以下よりご覧ください。

おまけ

警戒心が強めかな。

この記事が気に入ったらサポートをしてみませんか?