Get-CenAutoPilot.ps1

<#PSScriptInfo
  
.VERSION 4.0.6
  
.GUID ebf446a3-3362-4774-83c0-b7299410b63f
  
.AUTHOR Matthew Shortland
  
.COMPANYNAME Authlabs.io
  
.COPYRIGHT
  
.TAGS Windows AutoPilot PAW PAW-CSM
  
.RELEASENOTES
Version 4.0.0: Hacked at for PAW-CSM devices from the original get-windowsautopilotinfo.
Version 4.0.1: Forced the use of graph 2.25.0 as there is an auth bug in 2.26.o https://github.com/microsoftgraph/msgraph-sdk-powershell/issues/3197
Version 4.0.2: Had to change the install order of modules so 2.25 is used across dependencies
Version 4.0.3: ripped functions out of the windowsautopilotintune module so i dont have to download it
Version 4.0.4: added the intune module as a dependency
Version 4.0.5: Fixed auth error in function ripped from windowsautopilotintune, defaulting to DeviceLogin
Version 4.0.6: Fixed mistake in setting extensionattribute1
#>


<#
.SYNOPSIS
Retrieves the Windows AutoPilot deployment details from the local computer and assigns it to PAW-CSM
  
MIT LICENSE
  
Copyright (c) 2025 Matt Shortland
  
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
  
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
  
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  
.DESCRIPTION
This script uses WMI to retrieve properties needed for a customer to register a device with Windows Autopilot. Note that it is normal for the resulting CSV file to not collect a Windows Product ID (PKID) value since this is not required to register a device. Only the serial number and hardware hash will be populated.
.PARAMETER Name
The names of the computers. These can be provided via the pipeline (property name Name or one of the available aliases, DNSHostName, ComputerName, and Computer).
#>


[CmdletBinding(DefaultParameterSetName = 'Default')]
param(
    [Parameter(Mandatory=$False,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True,Position=0)][alias("DNSHostName","ComputerName","Computer")] [String[]] $Name = @("localhost")
)

Begin
{
    # Get NuGet
    $provider = Get-PackageProvider NuGet -ErrorAction Ignore
    if (-not $provider) {
        Write-Host "Installing provider NuGet"
        Find-PackageProvider -Name NuGet -ForceBootstrap -IncludeDependencies
    }

    # Get Graph Authentication module (and dependencies)
    $module = Import-Module microsoft.graph.authentication -PassThru -ErrorAction Ignore
    if (-not $module) {
            Write-Host "Installing module microsoft.graph.authentication"
            Install-Module microsoft.graph.authentication -RequiredVersion 2.25.0 -Force
    }
    Import-Module microsoft.graph.authentication -Scope Global
            
   # Get Graph Groups module (and dependencies)
    $module = Import-Module Microsoft.Graph.Groups -PassThru -ErrorAction Ignore
    if (-not $module)
    {
        Write-Host "Installing module Microsoft.Graph.Groups"
        Install-Module Microsoft.Graph.Groups -RequiredVersion 2.25.0 -Force
    }

    # Get Graph DirectoryManagement module (and dependencies)
    $module = Import-Module Microsoft.Graph.Identity.DirectoryManagement -PassThru -ErrorAction Ignore
    if (-not $module)
    {
        Write-Host "Installing module Microsoft.Graph.Identity.DirectoryManagement"
        Install-Module Microsoft.Graph.Identity.DirectoryManagement -RequiredVersion 2.25.0 -Force
    }

    # Get Graph Intune module (and dependencies)
    $module = Import-Module Microsoft.Graph.Intune -PassThru -ErrorAction Ignore
    if (-not $module)
    {
        Write-Host "Installing module Microsoft.Graph.Intune"
        Install-Module Microsoft.Graph.Intune -Force
    }

Function BoolToString() {
    param
    (
        [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$True)] [bool] $value
    )

    Process {
        return $value.ToString().ToLower()
    }
}

Function Get-AutopilotDevice(){
    [cmdletbinding()]
    param
    (
        [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$True)] $id,
        [Parameter(Mandatory=$false)] $serial,
        [Parameter(Mandatory=$false)] [Switch]$expand = $false
    )

    Process {

        # Defining Variables
        $graphApiVersion = "beta"
        $Resource = "deviceManagement/windowsAutopilotDeviceIdentities"
    
        if ($id -and $expand) {
            $uri = "https://graph.microsoft.com/$graphApiVersion/$($Resource)/$($id)?`$expand=deploymentProfile,intendedDeploymentProfile"
        }
        elseif ($id) {
            $uri = "https://graph.microsoft.com/$graphApiVersion/$($Resource)/$id"
        }
        elseif ($serial) {
            $encoded = [uri]::EscapeDataString($serial)
            $uri = "https://graph.microsoft.com/$graphApiVersion/$($Resource)?`$filter=contains(serialNumber,'$encoded')"
        }
        else {
            $uri = "https://graph.microsoft.com/$graphApiVersion/$($Resource)"
        }

        Write-Verbose "GET $uri"

        try {
            $response = Invoke-MgGraphRequest -Uri $uri -Method Get
            if ($id) {
                $response
            }
            else {
                $devices = $response.value
                $devicesNextLink = $response."@odata.nextLink"
    
                while ($null -ne $devicesNextLink){
                    $devicesResponse = (Invoke-MgGraphRequest -Uri $devicesNextLink -Method Get)
                    $devicesNextLink = $devicesResponse."@odata.nextLink"
                    $devices += $devicesResponse.value
                }
    
                if ($expand) {
                    $devices | Get-AutopilotDevice -Expand
                }
                else
                {
                    $devices
                }
            }
        }
        catch {
            Write-Error $_.Exception 
            break
        }
    }
}    

Function Get-AutopilotImportedDevice(){
    [cmdletbinding()]
    param
    (
        [Parameter(Mandatory=$false)] $id = $null
    )
    
    # Defining Variables
    $graphApiVersion = "beta"
    if ($id) {
        $uri = "https://graph.microsoft.com/$graphApiVersion/deviceManagement/importedWindowsAutopilotDeviceIdentities/$id"
    }
    else {
        $uri = "https://graph.microsoft.com/$graphApiVersion/deviceManagement/importedWindowsAutopilotDeviceIdentities"
    }

    Write-Verbose "GET $uri"

    try {
        $response = Invoke-MgGraphRequest -Uri $uri -Method Get
        if ($id) {
            $response
        }
        else {
            $devices = $response.value
    
            $devicesNextLink = $response."@odata.nextLink"
    
            while ($null -ne $devicesNextLink){
                $devicesResponse = (Invoke-MgGraphRequest -Uri $devicesNextLink -Method Get)
                $devicesNextLink = $devicesResponse."@odata.nextLink"
                $devices += $devicesResponse.value
            }
    
            $devices
        }
    }
    catch {
            Write-Error $_.Exception 
            break
    }
    
}
    
Function Add-AutopilotImportedDevice(){
    [cmdletbinding()]
    param
    (
        [Parameter(Mandatory=$true)] $serialNumber,
        [Parameter(Mandatory=$true)] $hardwareIdentifier,
        [Parameter(Mandatory=$false)] [Alias("orderIdentifier")] $groupTag = "",
        [Parameter(ParameterSetName = "Prop2")][Alias("UPN")] $assignedUser = ""
    )

    # Defining Variables
    $graphApiVersion = "beta"
    $Resource = "deviceManagement/importedWindowsAutopilotDeviceIdentities"
    $uri = "https://graph.microsoft.com/$graphApiVersion/$Resource"
    $json = @"
{
    "@odata.type": "#microsoft.graph.importedWindowsAutopilotDeviceIdentity",
    "groupTag": "$groupTag",
    "serialNumber": "$serialNumber",
    "productKey": "",
    "hardwareIdentifier": "$hardwareIdentifier",
    "assignedUserPrincipalName": "$assignedUser",
    "state": {
        "@odata.type": "microsoft.graph.importedWindowsAutopilotDeviceIdentityState",
        "deviceImportStatus": "pending",
        "deviceRegistrationId": "",
        "deviceErrorCode": 0,
        "deviceErrorName": ""
    }
}
"@


    Write-Verbose "POST $uri`n$json"

    try {
        Invoke-MgGraphRequest -Uri $uri -Method Post -Body $json -ContentType "application/json"
    }
    catch {
        Write-Error $_.Exception 
        break
    }
}

    # Connect to graph using Pass thru auth
    Connect-MgGraph -Scopes "DeviceManagementServiceConfig.ReadWrite.All", "DeviceManagementManagedDevices.ReadWrite.All", "Device.ReadWrite.All", "Group.ReadWrite.All", "GroupMember.ReadWrite.All" -UseDeviceAuthentication
            $graph = Get-MgContext
    Write-Host "Connected to Intune tenant" $graph.TenantId
}

Process
{

    $bad = $false

    # Get a CIM session
    $session = New-CimSession

    # Get the common properties.
    Write-Verbose "Checking $comp"
    $serial = (Get-CimInstance -CimSession $session -Class Win32_BIOS).SerialNumber

    # Get the hash (if available)
    $devDetail = (Get-CimInstance -CimSession $session -Namespace root/cimv2/mdm/dmmap -Class MDM_DevDetail_Ext01 -Filter "InstanceID='Ext' AND ParentID='./DevDetail'")
    if ($devDetail -and (-not $Force))
    {
        $hash = $devDetail.DeviceHardwareData
    }
    else
    {
        $bad = $true
        $hash = ""
    }

    # If the hash isn't available, get the make and model
    if ($bad)
    {
        $cs = Get-CimInstance -CimSession $session -Class Win32_ComputerSystem
        $make = $cs.Manufacturer.Trim()
        $model = $cs.Model.Trim()
    }
    else
    {
        $make = ""
        $model = ""
    }

    # Getting the PKID is generally problematic for anyone other than OEMs, so let's skip it here
    $product = ""
    # Create a pipeline object
    $c = New-Object psobject -Property @{
        "Device Serial Number" = $serial
        "Windows Product ID" = $product
        "Hardware Hash" = $hash
        "Group Tag" = "PAW-CSM"
    }

    # Write the object to the pipeline or array
    if ($bad)
    {
        # Report an error when the hash isn't available
        Write-Error -Message "Unable to retrieve device hardware data (hash) from computer $comp" -Category DeviceError
    }
    else
    {
        $computers += $c
        Write-Host "Gathered details for device with serial number: $serial"
    }

        Remove-CimSession $session
    
}

End
{
    # Add the devices
    $importStart = Get-Date
    $imported = @()
    $computers | ForEach-Object {
        $imported += Add-AutopilotImportedDevice -serialNumber $_.'Device Serial Number' -hardwareIdentifier $_.'Hardware Hash' -groupTag $_.'Group Tag' -assignedUser $_.'Assigned User'
    }

    # Wait until the devices have been imported
    $processingCount = 1
    while ($processingCount -gt 0)
    {
        $current = @()
        $processingCount = 0
        $imported | ForEach-Object {
            $device = Get-AutopilotImportedDevice -id $_.id
            if ($device.state.deviceImportStatus -eq "unknown") {
                $processingCount = $processingCount + 1
            }
            $current += $device
        }
        $deviceCount = $imported.Length
        Write-Host "Waiting for $processingCount of $deviceCount to be imported"
        if ($processingCount -gt 0){
            Start-Sleep 30
        }
    }

    # Wait until the devices can be found in Intune (should sync automatically)
    $syncStart = Get-Date
    $processingCount = 1
    while ($processingCount -gt 0)
    {
        $autopilotDevices = @()
        $processingCount = 0
        $current | ForEach-Object {
            if ($device.state.deviceImportStatus -eq "complete") {
                $device = Get-AutopilotDevice -id $_.state.deviceRegistrationId
                if (-not $device) {
                    $processingCount = $processingCount + 1
                }
                $autopilotDevices += $device
            }    
        }
        $deviceCount = $autopilotDevices.Length
        Write-Host "Waiting for $processingCount of $deviceCount to be synced"
        if ($processingCount -gt 0){
            Start-Sleep 30
        }
    }
    $syncDuration = (Get-Date) - $syncStart
    $syncSeconds = [Math]::Ceiling($syncDuration.TotalSeconds)
    Write-Host "Device synced. Elapsed time to complete sync: $syncSeconds seconds"
    
    # Add the device to the specified AAD group

    $aadGroup = Get-MgGroup -Filter "DisplayName eq 'PAW-CSM-Devices'"
    $autopilotDevices | ForEach-Object {
        $aadDevice = Get-MgDevice -Search "deviceId:$($_.azureActiveDirectoryDeviceId)" -ConsistencyLevel eventual
        if ($aadDevice) {
            Write-Host "Adding device $($_.serialNumber) to group $AddToGroup"
            New-MgGroupMember -GroupId $($aadGroup.Id) -DirectoryObjectId $($aadDevice.Id)
            Write-Host "Added device to group $($aadGroup.DisplayName)"
            Write-Host "Setting ExtensionAttribute1 to PAW for $($_.serialNumber)"

            $updateBody = @{
                extensionAttributes = @{
                    extensionAttribute1 = "PAW"
                }
            }

            Update-MgDevice -DeviceId $($aadDevice.Id) -BodyParameter $updateBody
        }
        else {
            Write-Error "Unable to find Azure AD device with ID $($_.azureActiveDirectoryDeviceId)"
        }
    }                
       
    Write-Host -NoNewLine 'Press Q to return to shell or any other key to restart...'
    start-sleep -Seconds 5
    $keypress = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')
    if ($keypress.Character -ne "Q"){
        Restart-Computer -Force
    }
}