C1Autopilot.ps1
|
<#PSScriptInfo
.VERSION 0.2.0 .GUID 25194a42-18c8-4b59-aac8-cc2b10cd4533 .AUTHOR CIS-One .COMPANYNAME CIS-One .COPYRIGHT (c) CIS-One. All rights reserved. .TAGS Windows Autopilot Intune GDAP #> <# .SYNOPSIS Registers the current Windows device in classic Windows Autopilot. .DESCRIPTION Collects the hardware hash in memory, signs the operator in through the native Windows WAM prompt, and submits the registration to the secured C1 Autopilot API for an active GDAP customer. Run from an elevated Windows PowerShell session on a supported Windows device. #> [CmdletBinding(SupportsShouldProcess = $true)] param( [Parameter()] [ValidatePattern('^[0-9a-fA-F-]{36}$')] [string]$ClientId = '6a87f18c-ab0a-4ef9-bb1c-587ae884b8e0', [Parameter()] [ValidatePattern('^[0-9a-fA-F-]{36}$')] [string]$PartnerTenantId = '26aaae92-5737-48a2-b00c-27aff5b013e7', [Parameter()] [string]$ApiBaseUrl = 'https://funcautopilot.azurewebsites.net', [Parameter()] [string]$ApiScope = 'api://dc4f4b96-741e-4db3-96d3-64a703132cc3/Autopilot.Register', [Parameter()] [ValidateRange(60, 900)] [int]$ImportTimeoutSeconds = 300, [Parameter()] [ValidateRange(1, 30)] [int]$PollIntervalSeconds = 5 ) $script:C1AuthenticationModuleName = 'Microsoft.Graph.Authentication' $script:C1AuthenticationModuleMinimumVersion = [version]'2.36.1' $script:C1WasDotSourced = $MyInvocation.InvocationName -eq '.' function Get-C1AutopilotDeviceInfo { try { $deviceDetails = Get-CimInstance ` -Namespace 'root/cimv2/mdm/dmmap' ` -ClassName 'MDM_DevDetail_Ext01' ` -Filter "InstanceID='Ext' AND ParentID='./DevDetail'" ` -ErrorAction Stop } catch { throw "Windows could not provide the Autopilot hardware hash. Run this on a supported Windows device from an elevated PowerShell session. Details: $($_.Exception.Message)" } $hardwareHash = [string]$deviceDetails.DeviceHardwareData if ([string]::IsNullOrWhiteSpace($hardwareHash)) { throw 'Windows returned an empty Autopilot hardware hash.' } try { if ([Convert]::FromBase64String($hardwareHash).Length -eq 0) { throw 'The decoded hardware hash is empty.' } } catch { throw "Windows returned an invalid Autopilot hardware hash. Details: $($_.Exception.Message)" } $serialNumber = [string](Get-CimInstance -ClassName Win32_BIOS -ErrorAction Stop).SerialNumber $serialNumber = $serialNumber.Trim() if ([string]::IsNullOrWhiteSpace($serialNumber)) { throw 'Windows did not return a BIOS serial number; Autopilot registration cannot continue.' } $productId = [string](Get-CimInstance -ClassName Win32_OperatingSystem -ErrorAction Stop).SerialNumber $productId = $productId.Trim() if ([string]::IsNullOrWhiteSpace($productId)) { throw 'Windows did not return a Windows product ID; Autopilot registration cannot continue.' } [pscustomobject]@{ SerialNumber = $serialNumber WindowsProductId = $productId HardwareIdentifier = $hardwareHash } } function Test-C1ApiBaseUrl { param( [Parameter(Mandatory)] [string]$BaseUrl ) $uri = $null if (-not [Uri]::TryCreate($BaseUrl, [UriKind]::Absolute, [ref]$uri) -or ($uri.Scheme -ne 'https' -and -not ($uri.IsLoopback -and $uri.Scheme -eq 'http')) -or $uri.AbsolutePath -ne '/' -or -not [string]::IsNullOrWhiteSpace($uri.Query) -or -not [string]::IsNullOrWhiteSpace($uri.Fragment) -or -not [string]::IsNullOrWhiteSpace($uri.UserInfo)) { throw 'ApiBaseUrl must be an HTTPS API origin. HTTP is allowed only for localhost development.' } $uri } function Import-C1MsalAuthenticationModule { [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 $module = Get-Module -ListAvailable -Name $script:C1AuthenticationModuleName | Where-Object { $_.Version -ge $script:C1AuthenticationModuleMinimumVersion } | Sort-Object Version -Descending | Select-Object -First 1 if (-not $module) { Write-Host 'MSAL-authenticatiecomponent installeren vanuit PowerShell Gallery...' Install-Module ` -Name $script:C1AuthenticationModuleName ` -MinimumVersion $script:C1AuthenticationModuleMinimumVersion ` -Scope CurrentUser ` -Repository PSGallery ` -Force ` -ErrorAction Stop } Import-Module $script:C1AuthenticationModuleName ` -MinimumVersion $script:C1AuthenticationModuleMinimumVersion ` -ErrorAction Stop if (-not ('Microsoft.Identity.Client.Broker.BrokerExtension' -as [type])) { throw 'De MSAL.NET WAM-broker is niet beschikbaar; de API-aanmelding kan niet doorgaan.' } } function Get-C1AuthenticationWindowHandle { if (-not ('C1Autopilot.NativeWindow' -as [type])) { Add-Type -TypeDefinition @' using System; using System.Runtime.InteropServices; namespace C1Autopilot { public static class NativeWindow { [DllImport("kernel32.dll")] public static extern IntPtr GetConsoleWindow(); [DllImport("user32.dll", ExactSpelling = true)] public static extern IntPtr GetAncestor(IntPtr window, uint flags); } } '@ -ErrorAction Stop } $consoleWindow = [C1Autopilot.NativeWindow]::GetConsoleWindow() $window = [C1Autopilot.NativeWindow]::GetAncestor($consoleWindow, 3) if ($window -eq [IntPtr]::Zero) { throw 'Er is geen consolevenster beschikbaar voor de WAM-aanmelding. Start het script in Windows PowerShell vanuit een consolevenster.' } $window } function New-C1ApiClientApplication { param( [Parameter(Mandatory)] [string]$ClientId, [Parameter(Mandatory)] [string]$TenantId ) $builderType = [Microsoft.Identity.Client.PublicClientApplicationBuilder] $brokerMethod = [Microsoft.Identity.Client.Broker.BrokerExtension].GetMethod('WithBroker') if ($builderType -ne $brokerMethod.GetParameters()[0].ParameterType) { throw 'Er zijn verschillende MSAL-versies in deze sessie geladen. Sluit PowerShell, start powershell.exe opnieuw en voer C1Autopilot opnieuw uit zonder MSAL.PS te importeren.' } $builder = $builderType::Create($ClientId). WithAuthority("https://login.microsoftonline.com/$TenantId"). WithRedirectUri("ms-appx-web://Microsoft.AAD.BrokerPlugin/$ClientId") $options = New-Object Microsoft.Identity.Client.BrokerOptions([Microsoft.Identity.Client.BrokerOptions+OperatingSystems]::Windows) $options.Title = 'C1Autopilot' $builder = [Microsoft.Identity.Client.Broker.BrokerExtension]::WithBroker($builder, $options) $builder.Build() } function Get-C1ApiAccessToken { param( [Parameter(Mandatory)] [string]$ClientId, [Parameter(Mandatory)] [string]$TenantId, [Parameter(Mandatory)] [string]$Scope ) $application = New-C1ApiClientApplication -ClientId $ClientId -TenantId $TenantId $window = Get-C1AuthenticationWindowHandle $request = $application.AcquireTokenInteractive([string[]]@($Scope)).WithParentActivityOrWindow($window) $result = $request.ExecuteAsync().GetAwaiter().GetResult() $accessToken = [string]$result.AccessToken if ([string]::IsNullOrWhiteSpace($accessToken)) { throw 'Microsoft Entra heeft geen API-token teruggegeven.' } $accessToken } function Invoke-C1ApiRequest { param( [Parameter(Mandatory)] [ValidateSet('GET', 'POST')] [string]$Method, [Parameter(Mandatory)] [string]$Uri, [Parameter(Mandatory)] [string]$AccessToken, [Parameter()] [AllowEmptyString()] [string]$Body ) $request = @{ Method = $Method Uri = $Uri Headers = @{ Authorization = "Bearer $AccessToken"; Accept = 'application/json' } ErrorAction = 'Stop' } if ($PSBoundParameters.ContainsKey('Body')) { $request.Body = $Body $request.ContentType = 'application/json' } try { Invoke-RestMethod @request } catch { $statusCode = if ($_.Exception.Response) { [int]$_.Exception.Response.StatusCode } else { 0 } $apiError = [string]$_.ErrorDetails.Message if ($apiError -match '"error"\s*:\s*"([A-Z0-9_]+)"') { $apiError = $matches[1] } elseif ($apiError.Length -gt 160) { $apiError = '' } $suffix = if ([string]::IsNullOrWhiteSpace($apiError)) { '' } else { " $apiError" } throw "C1Autopilot API-aanroep mislukt (HTTP $statusCode).$suffix" } } function Get-C1GdapCustomers { param( [Parameter(Mandatory)] [string]$ApiBaseUrl, [Parameter(Mandatory)] [string]$AccessToken ) $response = Invoke-C1ApiRequest ` -Method GET ` -Uri "$($ApiBaseUrl.TrimEnd('/'))/api/customers" ` -AccessToken $AccessToken if ($null -eq $response.customers) { throw 'De API gaf geen klantlijst terug.' } @($response.customers | Sort-Object DisplayName) } function Select-C1GdapCustomer { param( [Parameter(Mandatory)] [AllowEmptyCollection()] [object[]]$Customers ) if ($Customers.Count -eq 0) { throw 'Er zijn geen actieve GDAP-klanten gevonden in de partnertenant.' } Write-Host '' Write-Host 'Actieve GDAP-klanten:' for ($index = 0; $index -lt $Customers.Count; $index++) { Write-Host ('[{0}] {1} ({2})' -f ($index + 1), $Customers[$index].DisplayName, $Customers[$index].TenantId) } while ($true) { $selection = Read-Host 'Kies een klantnummer (Q om te stoppen)' if ($selection -match '^[Qq]$') { throw 'Registratie geannuleerd.' } $number = 0 if ([int]::TryParse($selection, [ref]$number) -and $number -ge 1 -and $number -le $Customers.Count) { return $Customers[$number - 1] } Write-Host 'Ongeldige keuze. Voer een nummer uit de lijst in.' -ForegroundColor Yellow } } function Start-C1AutopilotImport { param( [Parameter(Mandatory)] [psobject]$Device, [Parameter(Mandatory)] [psobject]$Customer, [Parameter(Mandatory)] [string]$ApiBaseUrl, [Parameter(Mandatory)] [string]$AccessToken ) $body = [ordered]@{ customerTenantId = [string]$Customer.TenantId serialNumber = [string]$Device.SerialNumber windowsProductId = [string]$Device.WindowsProductId hardwareHash = [string]$Device.HardwareIdentifier } | ConvertTo-Json -Depth 4 -Compress $response = Invoke-C1ApiRequest ` -Method POST ` -Uri "$($ApiBaseUrl.TrimEnd('/'))/api/registrations" ` -AccessToken $AccessToken ` -Body $body if ([string]::IsNullOrWhiteSpace([string]$response.importId)) { throw 'De API heeft geen import-ID teruggegeven; de status kan niet worden gecontroleerd.' } $response } function Wait-C1AutopilotImport { param( [Parameter(Mandatory)] [psobject]$Import, [Parameter(Mandatory)] [string]$CustomerTenantId, [Parameter(Mandatory)] [string]$ApiBaseUrl, [Parameter(Mandatory)] [string]$AccessToken, [Parameter(Mandatory)] [ValidateRange(60, 900)] [int]$TimeoutSeconds, [Parameter(Mandatory)] [ValidateRange(1, 30)] [int]$IntervalSeconds ) $importId = [string]$Import.importId if ([string]::IsNullOrWhiteSpace($importId)) { throw 'De API gaf geen import-ID terug; de status kan niet worden gecontroleerd.' } $encodedId = [Uri]::EscapeDataString($importId) $encodedTenantId = [Uri]::EscapeDataString($CustomerTenantId) $url = "$($ApiBaseUrl.TrimEnd('/'))/api/registrations/$encodedId`?customerTenantId=$encodedTenantId" $current = $Import $deadline = (Get-Date).AddSeconds($TimeoutSeconds) while ($true) { $status = [string]$current.status if ($status -eq 'complete') { return $current } if ($status -eq 'error' -or $status -eq 'partial') { $details = @([string]$current.errorName, [string]$current.errorCode) | Where-Object { -not [string]::IsNullOrWhiteSpace($_) } throw "Autopilot-hashregistratie is mislukt (status: $status). $($details -join ' / ')" } if ((Get-Date) -ge $deadline) { throw "De import is geaccepteerd, maar Intune heeft de registratie niet binnen $TimeoutSeconds seconden bevestigd. Controleer de Windows Autopilot-apparatenlijst voordat je opnieuw probeert." } Start-Sleep -Seconds $IntervalSeconds $current = Invoke-C1ApiRequest -Method GET -Uri $url -AccessToken $AccessToken } } function Invoke-C1Autopilot { [CmdletBinding(SupportsShouldProcess = $true)] param( [Parameter(Mandatory)] [string]$ClientId, [Parameter(Mandatory)] [string]$PartnerTenantId, [Parameter(Mandatory)] [string]$ApiBaseUrl, [Parameter(Mandatory)] [string]$ApiScope, [Parameter(Mandatory)] [int]$ImportTimeoutSeconds, [Parameter(Mandatory)] [int]$PollIntervalSeconds ) $identity = [Security.Principal.WindowsIdentity]::GetCurrent() $principal = New-Object Security.Principal.WindowsPrincipal($identity) if (-not ($identity.IsSystem -or $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator))) { throw 'Start PowerShell as administrator. In Windows OOBE, use Shift+F10 to open the elevated command prompt.' } $apiUri = Test-C1ApiBaseUrl -BaseUrl $ApiBaseUrl $ApiBaseUrl = $apiUri.AbsoluteUri.TrimEnd('/') if ([string]::IsNullOrWhiteSpace($ApiScope)) { throw 'Geef de delegated API-scope op via -ApiScope.' } $device = Get-C1AutopilotDeviceInfo Write-Host "Apparaat gevonden: $($device.SerialNumber)" Write-Host 'Hardwarehash verzameld (de hash wordt niet op het scherm getoond of naar schijf geschreven).' Import-C1MsalAuthenticationModule $accessToken = $null try { Write-Host 'Meld aan met het partneraccount via Microsoft Entra ID. Gebruik de beschikbare FIDO2/passkey-optie.' $accessToken = Get-C1ApiAccessToken ` -ClientId $ClientId ` -TenantId $PartnerTenantId ` -Scope $ApiScope $customers = @(Get-C1GdapCustomers -ApiBaseUrl $ApiBaseUrl -AccessToken $accessToken) $customer = Select-C1GdapCustomer -Customers $customers Write-Host "Geselecteerde klant: $($customer.DisplayName)" if ($PSCmdlet.ShouldProcess("$($device.SerialNumber) in $($customer.DisplayName)", 'Register as a Windows Autopilot device')) { Write-Host 'Hardwarehash via de beveiligde API registreren...' $imported = Start-C1AutopilotImport ` -Device $device ` -Customer $customer ` -ApiBaseUrl $ApiBaseUrl ` -AccessToken $accessToken $registered = Wait-C1AutopilotImport ` -Import $imported ` -CustomerTenantId $customer.TenantId ` -ApiBaseUrl $ApiBaseUrl ` -AccessToken $accessToken ` -TimeoutSeconds $ImportTimeoutSeconds ` -IntervalSeconds $PollIntervalSeconds Write-Host '' Write-Host 'Windows Autopilot-registratie voltooid.' -ForegroundColor Green Write-Host "Serienummer: $($device.SerialNumber)" Write-Host "Klant: $($customer.DisplayName) ($($customer.TenantId))" Write-Host 'Wijs zo nodig nog een Windows Autopilot-implementatieprofiel toe in Intune.' } else { Write-Host 'WhatIf: er is geen hardwarehash naar de API verzonden.' } } finally { $accessToken = $null } } if (-not $script:C1WasDotSourced) { Invoke-C1Autopilot ` -ClientId $ClientId ` -PartnerTenantId $PartnerTenantId ` -ApiBaseUrl $ApiBaseUrl ` -ApiScope $ApiScope ` -ImportTimeoutSeconds $ImportTimeoutSeconds ` -PollIntervalSeconds $PollIntervalSeconds ` -WhatIf:$WhatIfPreference } |