2026年2月版 Intune の同期をスクリプトから実行する方法(Windows)

に公開

課題

Title: Intuneの同期をコマンドで今すぐ実行する
https://azuread.net/archives/9259

参考:検証機のタスクスケジューラの状態(Windows 11 25H2)

上記の通りに GUID が二つある状態となっております。

確認した内容

上記の GUID について以下のレジストリを確認すると二つとも Intune に紐づいた GUID ですが、微妙に内容が異なっておりました。

確認したレジストリキー

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Enrollments\{GUID}

レジストリ Discovery URL ProviderID
一つ目のレジストリ enrollment.manage.microsoft.com/enrollmentserver/discovery.svc Microsoft Device Management
二つ目のレジストリ discovery.dm.microsoft.com/EnrollmentConfiguration MS DM Server

二つの GUID の違いについて

enrollment.manage.microsoft.com/enrollmentserver/discovery.svcについて
  • 旧世代のサービスエンドポイントです。
  • プロトコルは SOAP over HTTPS(WS-Trust、WS-SecurityPolicy)が使われております。
  • 認証については、ユーザー認証または証明書認証です。

参考:[MS-MDE2]: Overview | Microsoft Learn

The Mobile Device Enrollment (MDE) protocol enables a device to be enrolled with a Device Management Service (DMS) through an Enrollment Service (ES), including the discovery of the Management Enrollment Service (MES) and enrollment with the ES. After a device is enrolled, the device can be managed with the DMS using MDM
(中略)
4. The enrollment client sends a Discover message (section 3.1.4.1.1.1) to the Discovery Service. The Discovery Service responds with a DiscoverResponse message (section 3.1.4.1.1.2) containing the Uniform Resource Locators (URLs) of service endpoints required for the following steps.

日本語訳:

モバイルデバイス登録(MDE)プロトコルは、登録サービス(ES)を介してデバイスをデバイス管理サービス(DMS)に登録することを可能にします。これには、管理登録サービス(MES)の検出とESへの登録が含まれます。デバイスが登録されると、MDMを使用してDMSでデバイスを管理できるようになります。
(中略)
4. 登録クライアントは、Discoveryメッセージ(セクション3.1.4.1.1.1)をDiscoveryサービスに送信します。Discoveryサービスは、以降の手順に必要なサービスエンドポイントのUniform Resource Locator(URL)を含むDiscoverResponseメッセージ(セクション3.1.4.1.1.2)で応答します。

discovery.dm.microsoft.com/EnrollmentConfiguration?api-version=1.0 について

Windows 宣言構成 (WinDC) 登録では、新しい DMClient CSP ポリシーを使用して、Windows デバイスのデュアル登録を容易にします。 このプロセスでは、特定の構成サービス プロバイダー (CSP) ポリシーを設定し、SyncML コマンドを実行して登録状態を管理します。

タスクスケジューラの状態について

以下の上記二つの GUID についてタスクスケジューラを確認すると、常に ProviderIDMicrosoft Device Management となっているタスクの方が早く開始していることが確認できました。

よって、Microsoft Device Management 側のタスクが実行されるように、 PowerShell のスクリプトを作成したいと思います。

スクリプト

GUID が二重で登録されていることを考慮したスクリプトは以下の通りです。このスクリプトを管理者として実行すると、同期が実行されます。

動作を確認した環境

  • Windows 11(25H2)
  • PowerShell 5.1

実際のスクリプト


#requires -RunAsAdministrator
[CmdletBinding(SupportsShouldProcess = $true)]
param(
    [string]$TargetAadResourceId = "https://manage.microsoft.com/",
    [switch]$Quick, # /q を付けて即時実行を狙う(任意)
    [string]$LogPath = "$PSScriptRoot\mdm-sync.log"
)

function Write-Log {
    param([string]$Message)
    $line = "[{0}] {1}" -f (Get-Date).ToString("yyyy-MM-dd HH:mm:ss"), $Message
    $line | Out-File -FilePath $LogPath -Append -Encoding UTF8
}

try {
    Write-Log "Start."

    # 1) EnterpriseMgmt 配下の全 GUID を列挙
    $taskPaths = Get-ScheduledTask -TaskPath "\Microsoft\Windows\EnterpriseMgmt\*" -ErrorAction Stop |
        Select-Object -ExpandProperty TaskPath -Unique

    $allGuids = $taskPaths |
        ForEach-Object { $_.TrimEnd('\') } |
        ForEach-Object { Split-Path -Path $_ -Leaf } |
        Where-Object { $_ -match '^[0-9A-Fa-f]{8}-([0-9A-Fa-f]{4}-){3}[0-9A-Fa-f]{12}$' } |
        Sort-Object -Unique

    if (-not $allGuids -or $allGuids.Count -eq 0) {
        throw "EnterpriseMgmt 配下の GUID が見つかりませんでした。"
    }

    Write-Log ("EnterpriseMgmt GUIDs: {0}" -f ($allGuids -join ", "))

    # 2) HKLM\SOFTWARE\Microsoft\Enrollments\<GUID> の AADResourceID が
    #    https://manage.microsoft.com/ のものを抽出
    $matched = foreach ($guid in $allGuids) {
        $regPath = "HKLM:\SOFTWARE\Microsoft\Enrollments\$guid"
        if (-not (Test-Path $regPath)) { continue }

        $p = Get-ItemProperty -Path $regPath -Name "AADResourceID" -ErrorAction SilentlyContinue
        if (-not $p) { continue }

        $aad = [string]$p.AADResourceID
        $normalized = $aad.Trim()

        if ($normalized -eq $TargetAadResourceId -or $normalized.TrimEnd('/') -eq $TargetAadResourceId.TrimEnd('/')) {
            [pscustomobject]@{ Guid = $guid; AADResourceID = $aad }
        }
    }

    if (-not $matched) {
        throw "AADResourceID が '$TargetAadResourceId' の Enrollment GUID が見つかりませんでした。"
    }

    Write-Log ("Matched GUIDs: {0}" -f (($matched | ForEach-Object { $_.Guid }) -join ", "))

    # 3) deviceenroller.exe /o "<GUID>" /c [/q] を実行
    $exe = Join-Path $env:windir "System32\deviceenroller.exe"
    if (-not (Test-Path $exe)) {
        throw "deviceenroller.exe が見つかりません: $exe"
    }

    foreach ($m in $matched) {
        $args = @("/o", $m.Guid, "/c")
        if ($Quick) { $args += "/q" }

        $argText = ($args | ForEach-Object { if ($_ -match '\s') { '"' + $_ + '"' } else { $_ } }) -join ' '

        if ($PSCmdlet.ShouldProcess("$exe $argText", "Run")) {
            Write-Log "Run: $exe $argText"
            $p = Start-Process -FilePath $exe -ArgumentList $args -Wait -PassThru -WindowStyle Hidden
            Write-Log ("ExitCode: {0} (GUID={1})" -f $p.ExitCode, $m.Guid)
        }
    }

    Write-Log "Done."
}
catch {
    Write-Log ("ERROR: {0}" -f $_.Exception.Message)
    throw
}


オプションについて

-TargetAadResourceId

  • 実行先の ResourceId を指定できます。
  • デフォルトでは https://manage.microsoft.com/ となります。

-Quick

  • deviceenroll.exe のオプションに /q を付与して、即時実行を行うようにします。

-LogPath

  • ログの出力先です。
  • デフォルトでは、$PSScriptRoot\mdm-sync.log(スクリプトが保存されているディレクトリ) です。

Discussion