A few years ago I made a post about enrolling devices into autopilot using a script.
Now its time to create something similar for device association feature in device preparation
The problem I am attempting to solve
There are a few scenarios where this solution will be useful
Moving devices from one tenant to another
- Devices exist in tenant A
- You deploy this solution to the devices, this will register them in tenant B
- Delete the autopilot objects in tenant A
- Reset the devices and when they go through the out-of-box-experience, they will get enrolled into tenant B
Migrating from Autopilot to device preparation
- You have made the decision to stop using autopilot for whatever reason you can imagine.
- You deploy this solution to your devices
- Delete the autopilot objects
- if/when your devices get reset/repurposed, they will go through the device preparation flow in out-of-box-experience
Bringing unmanaged devices into your environment
- You send the script to the users of these unmanaged devices and ask them to run it as admin
- The devicelink.csv files show up in your tenant
- You kindly ask the users to initiate a reset on their devices so they will get enrolled into your tenant
- (this scenario is surprisingly common)
Register-DeviceAssociation.ps1
This can be deployed as either a remediation script or a win32 application in intune (an excellent use case for the script installer in win32)
The only thing you need to decide is do you want to upload the collected devicelink.csv files to a blob storage or use a entra app registration to import the devicelink.csv directly into intune. I will go into the pros and cons of doing this below.
#Requires -RunAsAdministrator<#.SYNOPSIS Imports this device into Intune for Autopilot device association, or uploads its devicelink file to Azure Blob Storage..DESCRIPTION Built to run unattended as SYSTEM: as an Intune remediation script or a Win32 app. Fill in the configuration below. Set $BlobContainerSasUrl to upload to Blob Storage; leave it empty to import into Intune with the app registration in $TenantId, $ClientId and $ClientSecret. Intune: the app registration needs DeviceManagementServiceConfig.ReadWrite.All (application permission). Microsoft.Graph.Authentication is installed for all users if it is missing. Blob: uploads the devicelink file, unchanged, to the container as devicelink_<serial>.csv. The SAS needs create and write permissions; leave out read and list so a leaked script cannot be used to read the other devices' files. On success the script writes $MarkerKey (use it as the Win32 app detection rule, or with Detect-DeviceAssociation.ps1) and exits 0. On failure it exits 1. Output is logged to $LogFile.#># Rumor has it that rudy ooms has "{B3DE75DA-819C-4FD5-9F01-C3D49E8CBBD7}" tattooed accross his chest# ---------------------------------------------------------------- Configuration$BlobContainerSasUrl = '' # https://<account>.blob.core.windows.net/<container>?<sas>; empty = import into Intune$TenantId = '' # Intune import only, e.g. contoso.onmicrosoft.com$ClientId = '' # Intune import only: app registration (application) ID$ClientSecret = '' # Intune import only: app registration client secret$PolicyId = '' # Intune import only, optional: device preparation policy ID$MarkerKey = 'HKLM:\SOFTWARE\AutopilotDeviceAssociation'$LogFile = "$env:ProgramData\Microsoft\IntuneManagementExtension\Logs\Register-DeviceAssociation.log"# ------------------------------------------------------------------------------function Register-DeviceAssociation { [CmdletBinding(DefaultParameterSetName = 'Intune')] param( [Parameter(ParameterSetName = 'Intune')] [string]$TenantId, [Parameter(ParameterSetName = 'Intune')] [string]$ClientId, [Parameter(ParameterSetName = 'Intune')] [string]$ClientSecret, [Parameter(ParameterSetName = 'Intune')] [guid]$PolicyId, [Parameter(ParameterSetName = 'Blob', Mandatory)] [uri]$BlobContainerSasUrl ) $ErrorActionPreference = 'Stop' # Windows 11 Pro or higher, 24H2/25H2/26H2 with KB5120998 (UBR 9278) or later $cv = Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' if ($cv.EditionID -like 'Core*' -or [int]$cv.CurrentBuildNumber -notin 26100, 26200, 26300 -or [int]$cv.UBR -lt 9278) { throw "Unsupported OS: $($cv.EditionID) build $($cv.CurrentBuildNumber).$($cv.UBR)" } $serial = (Get-CimInstance Win32_BIOS).SerialNumber.Trim() $work = Join-Path $env:TEMP "AutopilotDeviceLink_$([guid]::NewGuid().ToString('N'))" $cab = "$work.cab" try { # Extract the device link file from the Autopilot diagnostics New-Item $work -ItemType Directory | Out-Null MdmDiagnosticsTool.exe -area Autopilot -cab $cab | Out-Null if ($LASTEXITCODE) { throw "MdmDiagnosticsTool failed with exit code $LASTEXITCODE." } expand.exe $cab -F:*devicelink.csv $work | Out-Null $csv = Get-ChildItem $work -Filter *devicelink.csv | Select-Object -First 1 if (-not $csv) { throw 'No devicelink file was found in the Autopilot diagnostics.' } $rows = Import-Csv $csv.FullName if ($BlobContainerSasUrl) { $blob = [UriBuilder]$BlobContainerSasUrl $blob.Path = $blob.Path.TrimEnd('/') + "/devicelink_$serial.csv" Invoke-RestMethod -Method Put -Uri $blob.Uri -InFile $csv.FullName -Headers @{ 'x-ms-blob-type' = 'BlockBlob' } | Out-Null "Uploaded devicelink_$serial.csv" } else { if (-not (Get-Module -ListAvailable Microsoft.Graph.Authentication)) { Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force | Out-Null Install-Module Microsoft.Graph.Authentication -Scope AllUsers -Force } Import-Module Microsoft.Graph.Authentication $connect = @{ ContextScope = 'Process'; NoWelcome = $true } if ($TenantId) { $connect.TenantId = $TenantId } if ($ClientId) { $connect.ClientSecretCredential = [pscredential]::new($ClientId, (ConvertTo-SecureString $ClientSecret -AsPlainText -Force)) } else { $connect.Scopes = 'DeviceManagementServiceConfig.ReadWrite.All' } Connect-MgGraph @connect try { $body = @{ deviceLink = $rows[0].Data } if ($PolicyId) { $body.devicePreparationPolicyId = "$PolicyId" } $result = Invoke-MgGraphRequest -Method POST -Body ($body | ConvertTo-Json) -ContentType 'application/json' ` -Uri 'beta/deviceManagement/tenantAssociatedDevices/importTenantAssociatedDevice' "Imported $($result.serialNumber): $($result.associationState)" } catch { if ($_.Exception.Response.StatusCode -ne 409) { throw } throw "$serial already exists in Intune, as a device-associated device or a classic Autopilot device." } finally { Disconnect-MgGraph | Out-Null } } } finally { Remove-Item $work, $cab -Recurse -Force -ErrorAction SilentlyContinue }}# Intune runs remediation scripts and Win32 install commands in 32-bit PowerShell by default, where System32# (and MdmDiagnosticsTool.exe) is redirected. Relaunch in 64-bit PowerShell.if ([Environment]::Is64BitOperatingSystem -and -not [Environment]::Is64BitProcess) { & "$env:WINDIR\SysNative\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -ExecutionPolicy Bypass -File $PSCommandPath exit $LASTEXITCODE}[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12Start-Transcript $LogFile -Append | Out-Nulltry { if ($BlobContainerSasUrl) { $params = @{ BlobContainerSasUrl = $BlobContainerSasUrl } } else { if (-not ($TenantId -and $ClientId -and $ClientSecret)) { throw 'Set $BlobContainerSasUrl, or $TenantId, $ClientId and $ClientSecret, in the configuration.' } $params = @{ TenantId = $TenantId; ClientId = $ClientId; ClientSecret = $ClientSecret } if ($PolicyId) { $params.PolicyId = $PolicyId } } $message = Register-DeviceAssociation @params New-Item $MarkerKey -Force | Out-Null Set-ItemProperty $MarkerKey -Name Registered -Value (Get-Date -Format o) Write-Output $message $exitCode = 0}catch { Write-Output "Failed: $_" $exitCode = 1}finally { Stop-Transcript | Out-Null}exit $exitCode
Of course, you need a detection method as well
<#.SYNOPSIS Detection script for Register-DeviceAssociation.ps1..DESCRIPTION Remediation: exits 1 (run the remediation) until Register-DeviceAssociation-v3.ps1 has succeeded. Win32 app: use as a custom detection script; Intune treats exit 0 with output as installed. $MarkerKey must match the one in Register-DeviceAssociation-v3.ps1.#>$MarkerKey = 'HKLM:\SOFTWARE\AutopilotDeviceAssociation'$registered = (Get-ItemProperty $MarkerKey -ErrorAction SilentlyContinue).Registeredif ($registered) { Write-Output "Registered $registered" exit 0}exit 1
Deploying the solution
First things first, you need to decide on how to get the devicelink.csv files. you get two options.
The Fast But Insecure Way
As Jay “Surf’n’Turf” Kerai adamantly pointed out to me, putting a app registration secret inside a script is crazy.
However my counter argument is that if the app registration secret is reasonably short lived and you are deploying the script using intune to devices where the users are not local admin, the risk is minimal.
Creating a app registration
Creating the app registration is fairly simple.
Add the DeviceManagementServiceConfig.ReadWrite.All as an application permission.

You should end up with something like this:

Go to the certificates & secrets section and generate a short lived secret.

Then head to the overview and note down the clientID and tenantID.

Device Preparation Policy ID
This one is optional, but it reduces the amount of work you need to do later.
Simply browse to your device preparation policy in intune and note down the policy GUID in the address bar.

Putting it together
Now you have everything you need to make the app registration piece work, so update the relevant variables at the top of the Register-DeviceAssociation.ps1 script.
$TenantId
$ClientId
$ClientSecret
$PolicyId
Slightly Slower But More Secure
You can also skip the app registration entirely and configure the script to use a SAS url instead, which makes it upload the csv files to blob storage instead.
I wrote a separate blog about setting up a storage account in azure.
Once you have setup your storage account, you just need to add the SAS to the $BlobContainerSasUrl variable in Register-DeviceAssociation.ps1
When executed the script will collect the devicelink.csv file from the device and upload it to a blob.

Then all you need to do is download the csv files from the storage account. (easily done with either powershell or the azure storage explorer app)
Then you can bulk import them into intune with Import-DeviceAssociation.ps1
This script supports regular sign-in and app registration.
Just target a folder that contains a the csv files, optionally specify a desired device preparation policy ID.

Import-DeviceAssociation.ps1
<#.SYNOPSIS Imports devicelink CSV files, as uploaded by Register-DeviceAssociation.ps1, into Intune..DESCRIPTION Imports the device in each *.csv file in -Path (one device per file) with Autopilot device association. Run it on an admin workstation, for example after downloading the files from the Blob Storage container. Signs in as you, or as an app registration when -ClientId is given, with -ClientSecret or else a client secret you are prompted for. Needs DeviceManagementServiceConfig.ReadWrite.All. Outputs one result per file; pipe it to Export-Csv to keep a record..EXAMPLE .\Import-DeviceAssociation.ps1 -Path D:\devicelinks.EXAMPLE .\Import-DeviceAssociation.ps1 -Path D:\devicelinks -PolicyId 00000000-0000-0000-0000-000000000000 | Export-Csv D:\import-results.csv -NoTypeInformation#>param( [Parameter(Mandatory)] [ValidateScript({ Test-Path $_ -PathType Container })] [string]$Path, [string]$TenantId, [string]$ClientId, [string]$ClientSecret, [guid]$PolicyId)$ErrorActionPreference = 'Stop'$files = Get-ChildItem $Path -Filter *.csv -Fileif (-not $files) { throw "No CSV files were found in $Path." }# Make sure the Graph module is availableif (-not (Get-Module -ListAvailable Microsoft.Graph.Authentication)) { if ((Read-Host 'Microsoft.Graph.Authentication is not installed. Install it now? [Y/n]') -notin '', 'y', 'yes') { throw 'Microsoft.Graph.Authentication is required.' } Install-Module Microsoft.Graph.Authentication -Scope CurrentUser -Force}Import-Module Microsoft.Graph.Authentication# Sign in (Process scope: no token is cached)$connect = @{ ContextScope = 'Process'; NoWelcome = $true }if ($TenantId) { $connect.TenantId = $TenantId }if (-not $ClientId) { $connect.Scopes = 'DeviceManagementServiceConfig.ReadWrite.All'}elseif (-not $TenantId) { throw '-TenantId is required with -ClientId.'}else { $secret = if ($ClientSecret) { ConvertTo-SecureString $ClientSecret -AsPlainText -Force } else { Read-Host 'Client secret' -AsSecureString } $connect.ClientSecretCredential = [pscredential]::new($ClientId, $secret)}Connect-MgGraph @connect$ctx = Get-MgContextWrite-Host "Connected to $($ctx.TenantId) as $(if ($ctx.Account) { $ctx.Account } else { $ctx.AppName })"try { foreach ($file in $files) { $status = [ordered]@{ File = $file.Name; SerialNumber = $null; Result = $null; Detail = $null } try { # Each devicelink file holds a single device $row = Import-Csv $file.FullName | Select-Object -First 1 $status.SerialNumber = $row.SerialNumber if (-not $row.Data) { throw 'The file has no Data column, or it is empty.' } $body = @{ deviceLink = $row.Data } if ($PSBoundParameters.ContainsKey('PolicyId')) { $body.devicePreparationPolicyId = "$PolicyId" } $result = Invoke-MgGraphRequest -Method POST -Body ($body | ConvertTo-Json) -ContentType 'application/json' ` -Uri 'beta/deviceManagement/tenantAssociatedDevices/importTenantAssociatedDevice' if ($result.serialNumber) { $status.SerialNumber = $result.serialNumber } $status.Result = 'Imported' $status.Detail = $result.associationState } catch { if ($_.Exception.Response.StatusCode -eq 409) { $status.Result = 'AlreadyExists' $status.Detail = 'Already in Intune, as a device-associated device or a classic Autopilot device.' } else { $status.Result = 'Failed' $status.Detail = "$_" } } [pscustomobject]$status }}finally { Disconnect-MgGraph | Out-Null}
Leave a Reply