Exchange Onlineの新規ユーザー登録の自動化

概要

「Active Directoryの新規ユーザー作成」→「Azure ADへ同期」→「Microsoft365ユーザー作成」→「Exchange Onlineの設定」を自動化する方法です。

 

前提条件

・Microsoft365の管理者アカウントを所持していること。
・「Active Directory(AD)」→「Azure AD Connect」→「Azure AD」の構成が設定されていること。
・「Azure AD」と「Microsoft365」が統合されていること。

 

一括登録コマンド

 

① ADとAzureADを手動同期するコマンドを作成します。(ファイル名を「AD_sync.ps1」とします。)

Start-ADSyncSyncCycle -PolicyType Delta

 

② CSVファイルの作成をします。先頭行が項目名となります。

ファイル名「UserID.csv」

UserID First
Name
Last
Name
Name1 Name2 Email Identity mail
NN
tel SMTP Sub1
test1 Taro Yamada 山田 太郎 taro@jp taro@jp Taro taro@com taro@net
test2 Jiro Suzuki 鈴木 次郎 jiro@jp jiro@jp Jiro jiro@com jiro@net

 

③ テキストエディタを開き、以下のコマンドを入力し「.ps1」の拡張子で保存します。
(適宜、変数の値などを変更して実行してください)

## 実行方法
# このファイルを右クリックし「PowerShellで実行」をクリックする。


## 変数
## ------------------------------------------------------------------------------------------------------------------------------
# PowerShellファイル名
$FileName = $myInvocation.MyCommand.name

# 日付
$Today = Get-Date -Format yyyyMMddhhmmss

# コマンド実行ディレクトリ
$CmdDir = "(コマンドを実行するためのファイルパスを指定)"

# 登録CSVファイル名
$CSVUserID = "UserID.csv"

# メール管理者用アドレス
$EmailAdmin = "(メール管理者のメールアドレス)"

# Active DirctoryのOU (修正)
$ADOU = "OU=oumain,DC=test,DC=test,DC=co,DC=jp"

## ログ取得開始
start-transcript -path $CmdDir\LOG\$FileName.txt -Append


## CSV設定ファイルの確認
## ------------------------------------------------------------------------------------------------------------------------------
# CSV変数
$ResultUserIDCSV = (Test-Path "$CmdDir\$CSVUserID")

# CSVの存在しない場合は終了する(メッセージを黄色に変更)
if(!$ResultUserIDCSV) {
    Write-Host "「$CmdDir\$CSVUserID」が存在しないためめ終了します"  -foregroundcolor Yellow
    Start-Sleep -s 5
    exit
}

## Microsoft365/Exchangeコマンド読み込み
## ------------------------------------------------------------------------------------------------------------------------------
# Microsoft365管理者パスワードを取得
$Password  = Get-Content "$CmdDir\PW\AdminPass" | ConvertTo-SecureString

# Microsoft365管理者のID、PWを取得しログイン
$Credential = New-Object System.Management.Automation.PSCredential "(Microsoft365の管理者アカウント)",$Password
Connect-ExchangeOnline -Credential $credential -ShowProgress $true

# Exchangeコマンド読み込み
#------------------------------------------------------------------------
$SccSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.compliance.protection.outlook.com/powershell-liveid/ -Credential $credential -Authentication "Basic" -AllowRedirection
Import-PSSession $SccSession -Prefix cc


## ADユーザー作成
## ------------------------------------------------------------------------------------------------------------------------------

# CSVファイルを取得し、ADユーザーの作成
Write-Host ""
Import-Csv "$CmdDir\$CSVUserID" | ForEach-Object {
    
    # CSVのユーザー情報の取得
    $UserID = $_.UserID
    $FirstName = $_.Firstname
    $LastName = $_.Lastname
    $Name1 = $_.Name1
    $Name2 = $_.Name2
    $Email = $_.Email

    # ユーザー設定確認
    try {
        Get-ADUser $UserID
        Write-Host "Active Directoryに登録されています"
        Write-Host ""
    } catch {
        # ADの作成
        New-ADuser $UserID `
            -GivenName "$FirstName" `
            -SurName "$LastName" `
            -DisplayName "$LastName $FirstName" `
            -UserPrincipalName "${UserID}@test.com" `
            -AccountPassword (ConvertTo-SecureString -AsPlainText "PASSWORD" -Force) `
            -Enabled $True `
            -Path "$ADOU" `
            -Description "$Name1$Name2" `
            -EmailAddress "$Email" `
            -PasswordNeverExpires $True `
            -CannotChangePassword $True
        # CN名の変更(初期はUserIDのため、ローマ字に変更。同姓同名の場合は数字の1を加える)
        try {
            dsmove "CN=$UserID,$ADOU" -newname "$LastName $FirstName" -q
            Write-Host ""
            if($LASTEXITCODE -ne 0){
                throw
            }
        } catch {
            dsmove "CN=$UserID,$ADOU" -newname "$LastName ${FirstName}1" -q
            Write-Host ""
        }
        Write-Host ""
        Write-Host "${UserID}をActive Directoryに登録しました"
        # 登録OUの表示
        Get-ADUser $UserID | Format-List DistinguishedName | Out-String -Stream | where-object { $_.trim() -ne "" }
        Write-Host ""
    } finally {
        # 既存ユーザーのメール登録
        Set-ADuser $UserID -EmailAddress "$Email"
    }
	
	
}

## 【任意】 メールアドレスエイリアスの登録(ProxyAddress)
## ------------------------------------------------------------------------------------------------------------------------------

Import-Csv "$CmdDir\$CSVUseID" | ForEach-Object{
    
    # ユーザー設定確認
    $CheckADUser = Get-ADUser $UserID

    if(!$CheckADUser -ne 0){
        Write-Host "${UserID}はActive Directoryに登録されていません"
    } else {
        if($_.Identity -eq ""){
            $check1 = "Identityの値が入っていない行ですので、Identity値が入っていない行の属性値追加は行いませんでした";
            Write-Host $check1
        } elseif($_.mailNN -eq "" -or $_.SMTP -eq "") {
            $check2 = $_.Identity + "のmailNicknameまたはSMTPの値がありませんでしたので、" + $_.Identity +"行の属性値追加は行いませんでした"
            Write-Host $check2
        } else {
            Set-ADUser $_.Identity -Add @{ mailNickname = $_.mailNN }
            if($_.HideAddress -eq "TRUE"){
				Set-ADUser $_.Identity -replace @{ msExchHideFromAddressLists = $True }
			}
            if($_.tel -ne ""){
			Set-ADUser $_.Identity -Add @{ telephoneNumber = $_.tel }
			}
            $SMTP = "SMTP:" + $_.SMTP;Set-ADUser -Identity $_.Identity -Add @{ Proxyaddresses = $SMTP }
			
            if($_.sub1 -ne ""){
				$sub1 = "smtp:" + $_.sub1;Set-ADUser -Identity $_.Identity -Add @{ Proxyaddresses = $sub1
			}
            $check3 = $_.Identity + "をActive Directory(ProxyAddresses)に登録しました"
            Write-Host $check3;
        }
    }
}
Write-Host ""


## AzureADへ手動同期
## ------------------------------------------------------------------------------------------------------------------------------
Invoke-Command -ComputerName "(Azure AD Connectがインストールされているサービスのホスト名)" -FilePath $CmdDir\AD_sync.ps1


## Office365の設定
## ------------------------------------------------------------------------------------------------------------------------------

Import-Csv "$CmdDir\$CSVUserID" | ForEach-Object {

    # ユーザー情報
    $UserID = $_.UserID

    Write-Host "${UserID}のOffice365ユーザー登録の確認中"
	
    $ErrorActionPreference = "silentlycontinue"
    $CheckMsolUser = Get-MsolUser -UserPrincipalName "${UserID}@test.com"
	
    # Office365のユーザー情報が登録されるまでループさせる
    while(!$CheckMsolUser -ne 0) {
        $CheckMsolUser = Get-MsolUser -UserPrincipalName "${UserID}@test.com"
        Start-Sleep -s 5
        Write-Host -NoNewline '.'
    }
    $ErrorActionPreference = "continue"
    Write-Host ""

    # 設定場所の指定
    Set-MsolUser -UserPrincipalName "${UserID}@test.com" -UsageLocation JP

    # 不要なライセンスのチェックを外す
    $UserLicenseOptions = New-MsolLicenseOptions -AccountSkuId "COMPANY:ENTERPRISEPACK" -DisabledPlans "KAIZALA_O365_P3","MICROSOFT_SEARCH","WHITEBOARD_PLAN2","MIP_S_CLP1","BPOS_S_TODO_2","FORMS_PLAN_E3","STREAM_O365_E3","Deskless","FLOW_O365_P2","POWERAPPS_O365_P2","TEAMS1","PROJECTWORKMANAGEMENT","SWAY","INTUNE_O365","YAMMER_ENTERPRISE","RMS_S_ENTERPRISE","MCOSTANDARD","SHAREPOINTWAC","SHAREPOINTENTERPRISE"

    # ユーザーにライセンスを付与
    $CheckMsolUserLisence =  Get-MsolUser -UserPrincipalName "${UserID}@test.com" | Format-List Licenses  | Out-String -Stream | where-object { $_.trim() -ne "" } | Select-String COMPANY
	
    # 既存登録ユーザーはAddLicensesの設定不要
    if($CheckMsolUserLisence){
        Set-MsolUserLicense -UserPrincipalName "${UserID}@test.com" -LicenseOptions $UserLicenseOptions
    } else {
        # 新規登録ユーザーはAddLicensesを設定
        Set-MsolUserLicense -UserPrincipalName "${UserID}@test.com" -AddLicenses "COMPANY:ENTERPRISEPACK" -LicenseOptions $UserLicenseOptions
    }
    Write-Host "${UserID}にOffice365のライセンスを付与しました"

    # メールボックスの作成するまでループさせる
    Write-Host ""
    Write-Host "${UserID}のメールボックスを確認中"
    $ErrorActionPreference = "silentlycontinue"
    $CheckMailbox = Get-Mailbox -Identity "${UserID}@test.com" 2>Out-Null
    while(!$CheckMailbox -ne 0) {
        $CheckMailbox = Get-Mailbox -Identity "${UserID}@test.com" 2>Out-Null
        Start-Sleep -s 5
        Write-Host -NoNewline '.'
    }
    $ErrorActionPreference = "continue"
    
    Write-Host ""
    Write-Host "${UserID}のメールボックスが作成されました"
    Write-Host ""
    
    # 国、時刻の設定
    Set-MailboxRegionalConfiguration -Identity "${UserID}@test.com" -Language ja-jp -DateFormat "yyyy/MM/dd" -TimeFormat "HH:mm" -TimeZone "Tokyo Standard Time" -LocalizeDefaultFolderName:$True

    # メール接続方法の設定 (POP,IMAP,ActiveSynceがNG)
    Set-CASMailbox -Identity "${UserID}@test.com" -PopEnabled $False -ImapEnabled $False -ActiveSyncEnabled $False

    # 訴訟ホールドを有効化
    Write-Host "訴訟ホールド設定"
    Set-Mailbox -Identity "${UserID}@test.com" -LitigationHoldEnabled $True

    # スケジュールの設定
    Set-MailboxFolderPermission -Identity "${UserID}@test.com:\calender" -User "${UserID}@test.com" -AccessRights Reviewer

    # メール管理者のアクセス権設定
    Write-Host ""
    Write-Host "-------------------------------------------------------------"
    Add-MailboxPermission -Identity "${UserID}@test.com" -User $EmailAdmin -AccessRights FullAccess -InheritanceType All -AutoMapping $false
    Write-Host "-------------------------------------------------------------"
    Write-Host ""

    # 内容チェック
    #------------------------------------------------------------------------
    # 国(日本語)
    $CheckLanguage = Get-MailboxRegionalConfiguration "${UserID}@test.com" | Where-Object { $_.Language -eq "ja-JP" }
    # 年月日
    $CheckDateFormat = Get-MailboxRegionalConfiguration "${UserID}@test.com" | Where-Object { $_.DateFormat -eq "yyyy/MM/dd" }
    # 時刻
    $CheckTimeFormat = Get-MailboxRegionalConfiguration "${UserID}@test.com" | Where-Object { $_.TimeFormat -eq "HH:mm" }
    # タイムゾーン
    $CheckTimeZone = Get-MailboxRegionalConfiguration "${UserID}@test.com" | Where-Object { $_.TimeZone -eq "Tokyo Standard Time" }
    # Active Sync オフ
    $CheckActiveSyncEnabled = Get-CASMailbox "${UserID}@test.com" | Where-Object { $_.ActiveSyncEnabled -eq "" }
    # Ootw オン
    $CheckOWAEnabled = Get-CASMailbox "${UserID}@test.com" | Where-Object { $_.OWAEnabled -eq "True" }
    # POP接続 オフ
    $CheckPopEnabled = Get-CASMailbox "${UserID}@test.com" | Where-Object { $_.PopEnabled -eq "" }
    # IMAP接続 オフ
    $CheckImapEnabled = Get-CASMailbox "${UserID}@test.com" | Where-Object { $_.ImapEnabled -eq "" }
    # MAPI接続 オン
    $CheckMapiEnabled = Get-CASMailbox "${UserID}@test.com" | Where-Object { $_.MapiEnabled -eq "True" }
    # SMTP オン
    $CheckSmtpClientAuthenticationDisabled = Get-CASMailbox "${UserID}@test.com" | Where-Object { $_.SmtpClientAuthenticationDisabled -eq "" }
    # 訴訟ホールド オン
    $CheckLitigationHold = Get-Mailbox "${UserID}@test.com" | Format-List LitigationHoldEnabled | Out-String -Stream |where-object { $_.trim() -ne "" } | Select-String True
    # 予定表の権限付与
    $CheckFolderPermission = Get-MailboxFolderPermission "${UserID}@test.com:\予定表" | Where-Object {$_.AccessRights -eq "Reviewer" }
    # メール管理者のアクセス権付与
    $CheckMailboxPermission = Get-MailboxPermission "test-y@test.com" | Where-Object { $_.User -eq "EmailAdministrator_ML" }


    Write-Host "${UserID}の登録結果"
    Write-Host "-------------------------------------------------------------"

    if( [string]::IsNullOrEmpty($CheckLanguage) ){
        Write-Host "Check Language is NG" -foregroundcolor Red
    } else {
        Write-Host "Check Language is OK"
    }

    if( [string]::IsNullOrEmpty($CheckDateFormat) ){
        Write-Host "Check DateFormat is NG" -foregroundcolor Red
    } else {
        Write-Host "Check DateFormat is OK"
    }

    if( [string]::IsNullOrEmpty($CheckTimeFormat) ){
        Write-Host "Check TimeFormat is NG" -foregroundcolor Red
    } else {
        Write-Host "Check TimeFormat is OK"
    }

    if( [string]::IsNullOrEmpty($CheckTimeZone) ){
        Write-Host "Check TimeZone is NG" -foregroundcolor Red
    } else {
        Write-Host "Check TimeZone is OK"
    }

    if( [string]::IsNullOrEmpty($CheckActiveSyncEnabled) ){
        Write-Host "Check ActiveSync Disabled is NG" -foregroundcolor Red
    } else {
        Write-Host "Check ActiveSync Disabled is OK"
    }

    if( [string]::IsNullOrEmpty($CheckOWAEnabled) ){
        Write-Host "Check OWA Enabled is NG" -foregroundcolor Red
    } else {
        Write-Host "Check OWA Enabled is OK"
    }

    if( [string]::IsNullOrEmpty($CheckPopEnabled) ){
        Write-Host "Check POP3 Disabled is NG" -foregroundcolor Red
    } else {
        Write-Host "Check POP3 Disabled is OK"
    }

    if( [string]::IsNullOrEmpty($CheckImapEnabled) ){
        Write-Host "Check IMAP Disabled is NG" -foregroundcolor Red
    } else {
        Write-Host "Check IMAP Disabled is OK"
    }

    if( [string]::IsNullOrEmpty($CheckMapiEnabled) ){
        Write-Host "Check Mapi Enabled is NG" -foregroundcolor Red
    } else {
        Write-Host "Check Mapi Enabled is OK"
    }

    if( [string]::IsNullOrEmpty($CheckLitigationHold) ){
        Write-Host "Check LitigationHold is NG" -foregroundcolor Red
    } else {
        Write-Host "Check LitigationHold is OK"
    }

    if( [string]::IsNullOrEmpty($CheckSmtpClientAuthenticationDisabled) ){
        Write-Host "Check SmtpClientAuthenticationDisabled is OK"
    } else {
        Write-Host "Check SmtpClientAuthenticationDisabled is NG" -foregroundcolor Red
    }

    if( [string]::IsNullOrEmpty($CheckFolderPermission) ){
        Write-Host "Check FolderPermission is NG" -foregroundcolor Red
    } else {
        Write-Host "Check FolderPermission is OK"
    }

    if( [string]::IsNullOrEmpty($CheckMailboxPermission) ){
        Write-Host "Check MailboxPermission EmailAdministrator_ML is NG" -foregroundcolor Red
    } else {
        Write-Host "Check MailboxPermission EmailAdministrator_ML is OK"
    }
    
    Write-Host "-------------------------------------------------------------"

}

## ユーザー作成用ファイルの移動
Copy-Item $CmdDir\$CSVUserID $CmdDir\BK\$CSVUserID.bak.$Today

## エラー非表示Out-Nullファイル削除
Remove-Item $CmdDir\Out-Null

## ユーザー作成用ファイルの削除
Remove-Item $CmdDir\$CSVUserID

## ログ停止
Stop-Transcript
Write-Host ""

Pause