HashUP.ps1
|
<#PSScriptInfo .VERSION 4.4.1 .GUID 5c656be6-e65c-49f4-b6aa-756c6f97d3d9 .AUTHOR IAM (based on Microsoft's Get-WindowsAutopilotInfo) .COMPANYNAME .COPYRIGHT Based on Microsoft Get-WindowsAutopilotInfo, used under the MIT License. .TAGS Windows Autopilot Intune MicrosoftGraph OOBE .LICENSEURI https://opensource.org/license/mit .PROJECTURI .ICONURI .EXTERNALMODULEDEPENDENCIES Microsoft.Graph.Authentication .REQUIREDSCRIPTS .EXTERNALSCRIPTDEPENDENCIES .RELEASENOTES 4.4.0: - Email-first tenant discovery with a fixed single-tenant HashUP Client ID. - One interactive authentication through the dedicated app; no Graph CLI discovery sign-in. - Group Tag prompt; no Tenant ID confirmation. 4.3.0: - Removed the built-in AutoPilot Group Tag default. - Online dialog now requests Tenant ID, Client ID, and Group Tag together. - Group Tag may also be provided with -GroupTag; an empty value leaves it unset. 4.2.0: - Client ID and Tenant ID are intentionally not stored in this file. - When -Online is used and either ID is omitted, a two-field Windows dialog prompts for both values. - The dialog validates both values as GUIDs and uses them only for the current PowerShell process. - Falls back to Read-Host prompts if Windows Forms is unavailable. - Uses Microsoft's supported Microsoft.Graph.Authentication module and connects with the entered ClientId and TenantId, so the session uses the dedicated app rather than the shared Microsoft client. - Uses delegated interactive authentication and does not activate or check out a PIM role. - Group Tag has no built-in default and is entered alongside the app IDs for online runs. - Supports browser/WAM authentication by default and device-code authentication with -UseDeviceCode. - Loads Microsoft.Graph.Authentication from a Modules folder beside the script when available, otherwise installs it from PowerShell Gallery. - Performs an import-collection read preflight before uploading and prints the signed-in account, tenant, client, authentication type, and token scopes. - Uses DeviceManagementServiceConfig.ReadWrite.All for normal import operations and adds group scopes only when -AddToGroup or -AddToGroupId is used. - Preserves the BlockAADWorkplaceJoin registry safeguard and restores its prior state by default. #> <# .SYNOPSIS Collects a Windows Autopilot hardware hash and optionally uploads it through the specified app registration. .DESCRIPTION This script collects Windows Autopilot hardware information locally. With -Online, it prompts for the application identifiers when needed, then signs the technician in through the the selected Microsoft Entra app registration app registration and calls Microsoft Graph. The script uses Connect-MgGraph as the supported Microsoft authentication library and explicitly passes the ClientId and TenantId entered for the current run. It therefore does not use the shared Microsoft Graph Command Line Tools / Microsoft Graph PowerShell enterprise application. The Tenant ID is not stored in this file. The dedicated HashUP Client ID is configured in the script. When -Online is used and one or both values are omitted, the script displays a three-field dialog. The values are validated, held only in memory for the current process, and can also be supplied as command-line parameters. Application name: the selected Microsoft Entra app registration Normal upload permission: DeviceManagementServiceConfig.ReadWrite.All (Delegated) Additional permissions requested only for -AddToGroup or -AddToGroupId: Group.ReadWrite.All GroupMember.ReadWrite.All Device.Read.All The script does not use a client secret or certificate and does not activate a PIM role. .PARAMETER Name One or more computer names. The default is localhost. .PARAMETER OutputFile Optional CSV output path. When omitted in offline mode, the collected record is written to the pipeline. .PARAMETER GroupTag Optional Windows Autopilot Group Tag. No built-in default. In online mode, the dialog asks for it unless explicitly supplied. This does not add the device to an Entra group. .PARAMETER AssignedUser Optional user principal name to assign during import. .PARAMETER Append Append to an existing CSV instead of replacing it. .PARAMETER Credential Credential for a remote CIM session. It is not used for localhost. .PARAMETER Partner Create the Partner Center CSV schema. Cannot be combined with -Online. .PARAMETER Force Collect manufacturer and model even when a hardware hash is available. Retained for compatibility. .PARAMETER Online Upload the collected hardware hash to Windows Autopilot. .PARAMETER TenantId Microsoft Entra tenant ID. When omitted in online mode, the script prompts for it. .PARAMETER ClientId Application client ID. When omitted in online mode, the script prompts for it. Alias: AppId. .PARAMETER UseDeviceCode Use device-code authentication instead of the normal browser/WAM sign-in. .PARAMETER Scopes Additional delegated Microsoft Graph scopes. DeviceManagementServiceConfig.ReadWrite.All is always used. .PARAMETER AddToGroup Display name of an existing Entra security group to which the resulting device object should be added. Use -AddToGroupId when duplicate display names exist. .PARAMETER AddToGroupId Object ID of an existing Entra security group to which the resulting device object should be added. .PARAMETER AssignedComputerName Optional Autopilot computer name, applied after import and synchronization. .PARAMETER Assign Wait for deployment profile assignment. .PARAMETER Reboot Reboot after profile assignment. Requires -Assign. .PARAMETER KeepWorkplaceJoinBlock Leave BlockAADWorkplaceJoin set to 1. By default, its prior state is restored. .PARAMETER ImportTimeoutMinutes Maximum time to wait for import processing. .PARAMETER SyncTimeoutMinutes Maximum time to wait for the imported record to appear in the Autopilot inventory. .PARAMETER AssignmentTimeoutMinutes Maximum time to wait for deployment profile assignment. .PARAMETER PollSeconds Polling interval for import, synchronization, and profile assignment. .EXAMPLE .\HashUP_Clean.ps1 -Online Prompts for the Tenant ID, Client ID, and Group Tag, signs in through the dedicated application, and uploads the local computer's hardware hash. .EXAMPLE .\HashUP_Clean.ps1 -Online -UseDeviceCode Prompts for the application identifiers and uses device-code authentication. .EXAMPLE .\HashUP_Clean.ps1 -Online -GroupTag Regional-Autopilot Supplies the Group Tag for this run. .EXAMPLE .\HashUP_Clean.ps1 -OutputFile D:\hash.csv -GroupTag AutoPilot Collects the hardware hash to a CSV without signing in or prompting for application identifiers. .NOTES Use Start-Transcript outside this script when a support log is needed. MIT LICENSE Copyright (c) 2023 Microsoft 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. #> #Requires -Version 5.1 [CmdletBinding(DefaultParameterSetName = 'Offline')] param( [Parameter(Mandatory = $false, Position = 0)] [Alias('DNSHostName', 'ComputerName', 'Computer')] [string[]] $Name = @('localhost'), [Parameter(Mandatory = $false)] [string] $OutputFile = '', [Parameter(Mandatory = $false)] [string] $GroupTag = '', [Parameter(Mandatory = $false)] [string] $AssignedUser = '', [Parameter(Mandatory = $false)] [switch] $Append, [Parameter(Mandatory = $false)] [System.Management.Automation.PSCredential] $Credential, [Parameter(Mandatory = $false)] [switch] $Partner, [Parameter(Mandatory = $false)] [switch] $Force, [Parameter(Mandatory = $true, ParameterSetName = 'Online')] [switch] $Online, [Parameter(Mandatory = $false, ParameterSetName = 'Online')] [string] $Email = '', [Parameter(Mandatory = $false, ParameterSetName = 'Online')] [AllowEmptyString()] [string] $TenantId = '', [Parameter(Mandatory = $false, ParameterSetName = 'Online')] [Alias('AppId')] [AllowEmptyString()] [string] $ClientId = '', [Parameter(Mandatory = $false, ParameterSetName = 'Online')] [switch] $UseDeviceCode, [Parameter(Mandatory = $false, ParameterSetName = 'Online')] [string[]] $Scopes = @('DeviceManagementServiceConfig.ReadWrite.All'), [Parameter(Mandatory = $false, ParameterSetName = 'Online')] [string] $AddToGroup = '', [Parameter(Mandatory = $false, ParameterSetName = 'Online')] [string] $AddToGroupId = '', [Parameter(Mandatory = $false, ParameterSetName = 'Online')] [string] $AssignedComputerName = '', [Parameter(Mandatory = $false, ParameterSetName = 'Online')] [switch] $Assign, [Parameter(Mandatory = $false, ParameterSetName = 'Online')] [switch] $Reboot, [Parameter(Mandatory = $false, ParameterSetName = 'Online')] [switch] $KeepWorkplaceJoinBlock, [Parameter(Mandatory = $false, ParameterSetName = 'Online')] [ValidateRange(1, 120)] [int] $ImportTimeoutMinutes = 30, [Parameter(Mandatory = $false, ParameterSetName = 'Online')] [ValidateRange(1, 120)] [int] $SyncTimeoutMinutes = 30, [Parameter(Mandatory = $false, ParameterSetName = 'Online')] [ValidateRange(1, 240)] [int] $AssignmentTimeoutMinutes = 60, [Parameter(Mandatory = $false, ParameterSetName = 'Online')] [ValidateRange(5, 300)] [int] $PollSeconds = 15 ) Set-StrictMode -Version 1.0 $script:GraphBaseUri = 'https://graph.microsoft.com' $script:ApplicationDisplayName = 'the selected Microsoft Entra app registration' $script:GraphContext = $null $script:GraphConnected = $false $script:MinimumGraphAuthenticationVersion = [Version] '2.36.1' # Windows PowerShell 5.1 can otherwise negotiate an obsolete TLS version on some OOBE images. [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12 function Test-GuidValue { [CmdletBinding()] param( [Parameter(Mandatory = $true)] [AllowNull()] [AllowEmptyString()] [string] $Value ) if ([string]::IsNullOrWhiteSpace($Value)) { return $false } $parsed = [Guid]::Empty return [Guid]::TryParse($Value, [ref] $parsed) } function Get-TenantFromEmail { param([Parameter(Mandatory)][string] $Address) $Address = $Address.Trim() if ($Address -notmatch '^[^\s@]+@([A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)+)$') { throw 'Enter a valid organizational email address (for example, user@example.com).' } $domain = $Matches[1].ToLowerInvariant() # Microsoft Entra supports domain-based authority resolution for verified domains. # This is discovery only: the eventual authenticated Graph context is authoritative. $url = 'https://login.microsoftonline.com/{0}/v2.0/.well-known/openid-configuration' -f $domain try { $config = Invoke-RestMethod -Method Get -Uri $url -TimeoutSec 20 -ErrorAction Stop } catch { throw ('Could not discover a tenant for domain {0}. Domain discovery is not guaranteed for all domains or guest accounts. Details: {1}' -f $domain, $_.Exception.Message) } $issuer = [string]$config.issuer $match = [regex]::Match($issuer, '^https://login\.microsoftonline\.com/([0-9a-fA-F-]{36})/v2\.0/?$') if (-not $match.Success) { throw ('Discovery returned an unexpected issuer. Stopping rather than guessing the tenant: {0}' -f $issuer) } $tenantGuid = [guid]::Empty if (-not [guid]::TryParse($match.Groups[1].Value, [ref]$tenantGuid) -or $tenantGuid -eq [guid]::Empty) { throw 'Tenant discovery returned an invalid tenant identifier.' } return $tenantGuid.ToString() } function Read-GroupTag { try { Add-Type -AssemblyName System.Windows.Forms -ErrorAction Stop Add-Type -AssemblyName System.Drawing -ErrorAction Stop $form = New-Object System.Windows.Forms.Form $form.Text = 'HashUP - Workflow Test (No Upload)' $form.Size = New-Object System.Drawing.Size(440, 200) $form.StartPosition = 'CenterScreen' $form.FormBorderStyle = 'FixedDialog' $form.MaximizeBox = $false $form.MinimizeBox = $false $label = New-Object System.Windows.Forms.Label $label.Text = 'Autopilot Group Tag (optional):' $label.Location = New-Object System.Drawing.Point(20, 20) $label.AutoSize = $true $field = New-Object System.Windows.Forms.TextBox $field.Location = New-Object System.Drawing.Point(20, 49) $field.Width = 380 $ok = New-Object System.Windows.Forms.Button $ok.Text = 'Continue' $ok.Location = New-Object System.Drawing.Point(210, 100) $ok.DialogResult = [System.Windows.Forms.DialogResult]::OK $cancel = New-Object System.Windows.Forms.Button $cancel.Text = 'Cancel' $cancel.Location = New-Object System.Drawing.Point(315, 100) $cancel.DialogResult = [System.Windows.Forms.DialogResult]::Cancel $form.Controls.AddRange(@($label, $field, $ok, $cancel)) $form.AcceptButton = $ok $form.CancelButton = $cancel try { if ($form.ShowDialog() -ne [System.Windows.Forms.DialogResult]::OK) { throw [System.OperationCanceledException]::new('User cancelled Group Tag input.') } return $field.Text.Trim() } finally { $form.Dispose() } } catch [System.OperationCanceledException] { throw } catch { Write-Warning 'Windows Forms unavailable; using console input.' return ([string](Read-Host 'Group Tag (optional)')).Trim() } } function Initialize-GraphAuthenticationModule { [CmdletBinding()] param() $localModuleRoot = Join-Path -Path $PSScriptRoot -ChildPath 'Modules' if (Test-Path -LiteralPath $localModuleRoot) { $modulePaths = @($env:PSModulePath -split [IO.Path]::PathSeparator) if ($modulePaths -notcontains $localModuleRoot) { $env:PSModulePath = $localModuleRoot + [IO.Path]::PathSeparator + $env:PSModulePath } Write-Host ('Using local module search path: {0}' -f $localModuleRoot) } # Remove an old, user-defined Connect-MgGraph override that can shadow the real module command. $existingConnect = Get-Command -Name Connect-MgGraph -ErrorAction SilentlyContinue if ( $null -ne $existingConnect -and $existingConnect.CommandType -eq 'Function' -and [string]::IsNullOrWhiteSpace([string] $existingConnect.ModuleName) ) { Remove-Item -LiteralPath Function:\Connect-MgGraph -Force -ErrorAction SilentlyContinue } $candidate = Get-Module -ListAvailable -Name Microsoft.Graph.Authentication | Where-Object { $_.Version -ge $script:MinimumGraphAuthenticationVersion } | Sort-Object -Property Version -Descending | Select-Object -First 1 if ($null -eq $candidate) { Write-Host ('Microsoft.Graph.Authentication {0} or later is not installed. Installing it for the current user.' -f $script:MinimumGraphAuthenticationVersion) if ($null -eq (Get-Command -Name Install-Module -ErrorAction SilentlyContinue)) { throw 'Install-Module is unavailable. Pre-stage Microsoft.Graph.Authentication in a Modules folder beside this script.' } try { $nuget = Get-PackageProvider -Name NuGet -ListAvailable -ErrorAction SilentlyContinue | Sort-Object -Property Version -Descending | Select-Object -First 1 if ($null -eq $nuget) { Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Scope CurrentUser -Force -ErrorAction Stop | Out-Null } Install-Module -Name Microsoft.Graph.Authentication ` -MinimumVersion $script:MinimumGraphAuthenticationVersion ` -Scope CurrentUser ` -Repository PSGallery ` -Force ` -AllowClobber ` -ErrorAction Stop } catch { throw ('Unable to install Microsoft.Graph.Authentication. Connect the laptop to the internet or pre-stage the module under {0}. {1}' -f $localModuleRoot, $_.Exception.Message) } $candidate = Get-Module -ListAvailable -Name Microsoft.Graph.Authentication | Where-Object { $_.Version -ge $script:MinimumGraphAuthenticationVersion } | Sort-Object -Property Version -Descending | Select-Object -First 1 } if ($null -eq $candidate) { throw ('Microsoft.Graph.Authentication {0} or later could not be located after installation.' -f $script:MinimumGraphAuthenticationVersion) } # This script is designed for a dedicated OOBE PowerShell process. Unload Graph modules first # to reduce mixed-version assembly conflicts, then load one known Authentication module version. Get-Module -Name 'Microsoft.Graph*' | Remove-Module -Force -ErrorAction SilentlyContinue try { Import-Module -Name $candidate.Path -Force -ErrorAction Stop } catch { throw ('Unable to load Microsoft.Graph.Authentication {0}. Close all PowerShell windows, open a fresh powershell.exe -NoProfile window, and rerun the script. {1}' -f $candidate.Version, $_.Exception.Message) } foreach ($requiredCommand in @('Connect-MgGraph', 'Disconnect-MgGraph', 'Get-MgContext', 'Invoke-MgGraphRequest')) { if ($null -eq (Get-Command -Name $requiredCommand -Module Microsoft.Graph.Authentication -ErrorAction SilentlyContinue)) { throw ('Microsoft.Graph.Authentication loaded, but command {0} is unavailable.' -f $requiredCommand) } } Write-Host ('Loaded Microsoft.Graph.Authentication {0}.' -f $candidate.Version) } function Connect-AutopilotGraph { [CmdletBinding()] param( [Parameter(Mandatory = $true)] [string] $TenantId, [Parameter(Mandatory = $true)] [string] $ClientId, [Parameter(Mandatory = $true)] [string[]] $RequiredScopes, [Parameter(Mandatory = $false)] [switch] $UseDeviceCode ) try { Microsoft.Graph.Authentication\Disconnect-MgGraph -ErrorAction SilentlyContinue | Out-Null } catch { } $connectParameters = @{ ClientId = $ClientId TenantId = $TenantId Scopes = $RequiredScopes ContextScope = 'Process' NoWelcome = $true ErrorAction = 'Stop' } if ($UseDeviceCode) { $connectParameters['UseDeviceAuthentication'] = $true } Write-Host '' Write-Host ('Signing in through application: {0}' -f $script:ApplicationDisplayName) Write-Host ('Client ID: {0}' -f $ClientId) Write-Host ('Tenant ID: {0}' -f $TenantId) try { Microsoft.Graph.Authentication\Connect-MgGraph @connectParameters | Out-Null $script:GraphConnected = $true } catch { throw ('Microsoft Graph sign-in through {0} failed. {1}' -f $script:ApplicationDisplayName, $_.Exception.Message) } $context = Microsoft.Graph.Authentication\Get-MgContext if ($null -eq $context) { throw 'Connect-MgGraph returned without a Microsoft Graph context.' } if ([string] $context.ClientId -ne $ClientId) { throw ('The Graph session used client ID {0}, not the configured application {1}.' -f $context.ClientId, $ClientId) } if ([string] $context.TenantId -ne $TenantId) { throw ('The Graph session used tenant {0}, not the configured tenant {1}.' -f $context.TenantId, $TenantId) } if ([string] $context.AuthType -ne 'Delegated') { throw ('Expected delegated authentication, but Graph reported AuthType {0}.' -f $context.AuthType) } $grantedScopes = @($context.Scopes | ForEach-Object { [string] $_ }) $missingScopes = @() foreach ($scope in $RequiredScopes) { if ($grantedScopes -notcontains $scope) { $missingScopes += $scope } } if ($missingScopes.Count -gt 0) { throw ('The access token does not contain the required delegated scope(s): {0}. Confirm the app permissions and admin consent.' -f ($missingScopes -join ', ')) } $script:GraphContext = $context $script:GraphConnected = $true Write-Host '' Write-Host ('Signed in as: {0}' -f $context.Account) Write-Host ('Tenant ID: {0}' -f $context.TenantId) Write-Host ('Client ID: {0}' -f $context.ClientId) Write-Host ('Auth type: {0}' -f $context.AuthType) Write-Host ('Token scopes: {0}' -f ($grantedScopes -join ', ')) } function Get-GraphErrorInfo { [CmdletBinding()] param( [Parameter(Mandatory = $true)] [System.Management.Automation.ErrorRecord] $ErrorRecord ) $statusCode = 0 $code = '' $message = $ErrorRecord.Exception.Message $body = '' $requestId = '' $clientRequestId = '' $retryAfter = 0 try { $statusCode = [int] $ErrorRecord.Exception.ResponseStatusCode } catch { } if ($statusCode -eq 0) { try { $statusCode = [int] $ErrorRecord.Exception.StatusCode } catch { } } if ($statusCode -eq 0) { try { $statusCode = [int] $ErrorRecord.Exception.Response.StatusCode } catch { } } try { $body = [string] $ErrorRecord.ErrorDetails.Message } catch { } if ([string]::IsNullOrWhiteSpace($body)) { try { $body = [string] $ErrorRecord.Exception.ResponseBody } catch { } } try { $headers = $ErrorRecord.Exception.ResponseHeaders if ($null -ne $headers) { try { $requestId = [string] $headers['request-id'] } catch { } try { $clientRequestId = [string] $headers['client-request-id'] } catch { } try { $retryAfter = [int] $headers['Retry-After'] } catch { } } } catch { } if (-not [string]::IsNullOrWhiteSpace($body)) { try { $parsed = $body | ConvertFrom-Json -ErrorAction Stop if ($null -ne $parsed.error) { if ($parsed.error -is [string]) { $code = [string] $parsed.error } else { if ($null -ne $parsed.error.code) { $code = [string] $parsed.error.code } if ($null -ne $parsed.error.message) { $message = [string] $parsed.error.message } if ($null -ne $parsed.error.innerError) { if ([string]::IsNullOrWhiteSpace($requestId) -and $null -ne $parsed.error.innerError.'request-id') { $requestId = [string] $parsed.error.innerError.'request-id' } if ([string]::IsNullOrWhiteSpace($clientRequestId) -and $null -ne $parsed.error.innerError.'client-request-id') { $clientRequestId = [string] $parsed.error.innerError.'client-request-id' } } } } } catch { } } if ($statusCode -eq 0 -and $message -match '\b(400|401|403|404|409|429|500|502|503|504)\b') { $statusCode = [int] $Matches[1] } return [pscustomobject]@{ StatusCode = $statusCode Code = $code Message = $message Body = $body RequestId = $requestId ClientRequestId = $clientRequestId RetryAfter = $retryAfter } } function Invoke-CustomGraphRequest { [CmdletBinding()] param( [Parameter(Mandatory = $true)] [ValidateSet('GET', 'POST', 'PATCH', 'PUT', 'DELETE')] [string] $Method, [Parameter(Mandatory = $true)] [string] $Uri, [Parameter(Mandatory = $false)] [object] $Body, [Parameter(Mandatory = $false)] [hashtable] $AdditionalHeaders, [Parameter(Mandatory = $false)] [ValidateRange(1, 10)] [int] $MaximumAttempts = 4 ) for ($attempt = 1; $attempt -le $MaximumAttempts; $attempt++) { $parameters = @{ Method = $Method Uri = $Uri ErrorAction = 'Stop' } if ($null -ne $AdditionalHeaders -and $AdditionalHeaders.Count -gt 0) { $parameters['Headers'] = $AdditionalHeaders } if ($null -ne $Body) { $parameters['Body'] = ($Body | ConvertTo-Json -Depth 20 -Compress) $parameters['ContentType'] = 'application/json' } try { return Microsoft.Graph.Authentication\Invoke-MgGraphRequest @parameters } catch { $info = Get-GraphErrorInfo -ErrorRecord $_ $isIdempotent = $Method -in @('GET', 'PUT', 'PATCH', 'DELETE') $retryable = ( ($info.StatusCode -eq 429) -or ($isIdempotent -and $info.StatusCode -in @(500, 502, 503, 504)) ) if ($retryable -and $attempt -lt $MaximumAttempts) { $delay = $info.RetryAfter if ($delay -le 0) { $delay = [Math]::Min(60, [int] [Math]::Pow(2, $attempt)) } Write-Warning ('Graph returned HTTP {0}. Retrying in {1} second(s), attempt {2} of {3}.' -f $info.StatusCode, $delay, ($attempt + 1), $MaximumAttempts) Start-Sleep -Seconds $delay continue } $details = @() if ($info.StatusCode -gt 0) { $details += ('HTTP={0}' -f $info.StatusCode) } if (-not [string]::IsNullOrWhiteSpace($info.Code)) { $details += ('Code={0}' -f $info.Code) } if (-not [string]::IsNullOrWhiteSpace($info.Message)) { $details += ('Message={0}' -f $info.Message) } if (-not [string]::IsNullOrWhiteSpace($info.RequestId)) { $details += ('RequestId={0}' -f $info.RequestId) } if (-not [string]::IsNullOrWhiteSpace($info.ClientRequestId)) { $details += ('ClientRequestId={0}' -f $info.ClientRequestId) } $exceptionMessage = 'Microsoft Graph request failed: {0} {1}. {2}' -f $Method, $Uri, ($details -join '; ') $exception = New-Object System.Exception -ArgumentList @($exceptionMessage, $_.Exception) $exception.Data['StatusCode'] = $info.StatusCode $exception.Data['GraphCode'] = $info.Code $exception.Data['GraphMessage'] = $info.Message $exception.Data['RequestId'] = $info.RequestId $exception.Data['ClientRequestId'] = $info.ClientRequestId $exception.Data['ResponseBody'] = $info.Body throw $exception } } } function Enable-TemporaryWorkplaceJoinBlock { [CmdletBinding()] param() $path = 'HKLM:\SOFTWARE\Policies\Microsoft\Windows\WorkplaceJoin' $name = 'BlockAADWorkplaceJoin' $pathExisted = Test-Path -LiteralPath $path $valueExisted = $false $oldValue = $null if ($pathExisted) { $existing = Get-ItemProperty -LiteralPath $path -Name $name -ErrorAction SilentlyContinue if ($null -ne $existing) { $valueExisted = $true $oldValue = $existing.$name } } try { if (-not $pathExisted) { New-Item -Path $path -Force -ErrorAction Stop | Out-Null } New-ItemProperty -LiteralPath $path -Name $name -PropertyType DWord -Value 1 -Force -ErrorAction Stop | Out-Null } catch { throw ('Unable to set the temporary Workplace Join block. Run this script from an elevated PowerShell window. {0}' -f $_.Exception.Message) } Write-Host 'Temporarily set BlockAADWorkplaceJoin=1.' return [pscustomobject]@{ Path = $path Name = $name PathExisted = $pathExisted ValueExisted = $valueExisted OldValue = $oldValue } } function Restore-WorkplaceJoinBlock { [CmdletBinding()] param( [Parameter(Mandatory = $true)] [object] $State ) try { if ($State.ValueExisted) { New-ItemProperty -LiteralPath $State.Path -Name $State.Name -PropertyType DWord -Value ([int] $State.OldValue) -Force -ErrorAction Stop | Out-Null Write-Host ('Restored BlockAADWorkplaceJoin to its previous value: {0}.' -f $State.OldValue) } else { Remove-ItemProperty -LiteralPath $State.Path -Name $State.Name -ErrorAction SilentlyContinue Write-Host 'Removed the temporary BlockAADWorkplaceJoin value.' if (-not $State.PathExisted -and (Test-Path -LiteralPath $State.Path)) { $item = Get-Item -LiteralPath $State.Path -ErrorAction SilentlyContinue if ($null -ne $item -and @($item.Property).Count -eq 0 -and @($item.GetSubKeyNames()).Count -eq 0) { Remove-Item -LiteralPath $State.Path -Force -ErrorAction SilentlyContinue } } } } catch { Write-Warning ('Unable to restore the previous Workplace Join registry state: {0}' -f $_.Exception.Message) } } function Get-AutopilotHardwareRecord { [CmdletBinding()] param( [Parameter(Mandatory = $true)] [string] $ComputerName, [Parameter(Mandatory = $false)] [System.Management.Automation.PSCredential] $Credential, [Parameter(Mandatory = $false)] [switch] $Partner, [Parameter(Mandatory = $false)] [switch] $Force, [Parameter(Mandatory = $false)] [string] $GroupTag, [Parameter(Mandatory = $false)] [string] $AssignedUser ) $session = $null try { $isLocal = $ComputerName -in @('localhost', '.', $env:COMPUTERNAME) if ($isLocal) { $session = New-CimSession -ErrorAction Stop } else { if ($null -ne $Credential) { $session = New-CimSession -ComputerName $ComputerName -Credential $Credential -ErrorAction Stop } else { $session = New-CimSession -ComputerName $ComputerName -ErrorAction Stop } } Write-Verbose ('Collecting Autopilot information from {0}' -f $ComputerName) $bios = Get-CimInstance -CimSession $session -ClassName Win32_BIOS -ErrorAction Stop $serial = ([string] $bios.SerialNumber).Trim() if ([string]::IsNullOrWhiteSpace($serial)) { throw ('No BIOS serial number was returned by {0}.' -f $ComputerName) } $hardwareHash = '' $hashFailure = '' try { $deviceDetail = Get-CimInstance -CimSession $session -Namespace 'root/cimv2/mdm/dmmap' -ClassName 'MDM_DevDetail_Ext01' -Filter "InstanceID='Ext' AND ParentID='./DevDetail'" -ErrorAction Stop if ($null -ne $deviceDetail) { $hardwareHash = [string] $deviceDetail.DeviceHardwareData } } catch { $hashFailure = $_.Exception.Message } $manufacturer = '' $model = '' if ($Partner -or $Force) { $computerSystem = Get-CimInstance -CimSession $session -ClassName Win32_ComputerSystem -ErrorAction Stop $manufacturer = ([string] $computerSystem.Manufacturer).Trim() $model = ([string] $computerSystem.Model).Trim() } if ([string]::IsNullOrWhiteSpace($hardwareHash) -and -not $Partner) { $suffix = '' if (-not [string]::IsNullOrWhiteSpace($hashFailure)) { $suffix = ' ' + $hashFailure } throw ('Unable to retrieve the Windows Autopilot hardware hash from {0}.{1}' -f $ComputerName, $suffix) } Write-Host ('Gathered details for device with serial number: {0}' -f $serial) return [pscustomobject][ordered]@{ 'Device Serial Number' = $serial 'Windows Product ID' = '' 'Hardware Hash' = $hardwareHash 'Group Tag' = $GroupTag 'Assigned User' = $AssignedUser 'Manufacturer name' = $manufacturer 'Device model' = $model 'Source Computer' = $ComputerName } } finally { if ($null -ne $session) { Remove-CimSession -CimSession $session -ErrorAction SilentlyContinue } } } function Write-AutopilotCsv { [CmdletBinding()] param( [Parameter(Mandatory = $true)] [object[]] $Records, [Parameter(Mandatory = $true)] [string] $Path, [Parameter(Mandatory = $false)] [switch] $Append, [Parameter(Mandatory = $false)] [switch] $Partner, [Parameter(Mandatory = $false)] [string] $GroupTag, [Parameter(Mandatory = $false)] [string] $AssignedUser ) $fullPath = [IO.Path]::GetFullPath($Path) $directory = Split-Path -Path $fullPath -Parent if (-not [string]::IsNullOrWhiteSpace($directory) -and -not (Test-Path -LiteralPath $directory)) { New-Item -ItemType Directory -Path $directory -Force -ErrorAction Stop | Out-Null } $allRecords = @($Records) if ($Append -and (Test-Path -LiteralPath $fullPath)) { $allRecords = @(Import-Csv -LiteralPath $fullPath -ErrorAction Stop) + $allRecords } if ($Partner) { $properties = @('Device Serial Number', 'Windows Product ID', 'Hardware Hash', 'Manufacturer name', 'Device model') } elseif (-not [string]::IsNullOrWhiteSpace($AssignedUser)) { $properties = @('Device Serial Number', 'Windows Product ID', 'Hardware Hash', 'Group Tag', 'Assigned User') } elseif (-not [string]::IsNullOrWhiteSpace($GroupTag)) { $properties = @('Device Serial Number', 'Windows Product ID', 'Hardware Hash', 'Group Tag') } else { $properties = @('Device Serial Number', 'Windows Product ID', 'Hardware Hash') } $csvLines = @($allRecords | Select-Object -Property $properties | ConvertTo-Csv -NoTypeInformation | ForEach-Object { $_ -replace '"', '' }) $utf8WithoutBom = New-Object System.Text.UTF8Encoding -ArgumentList $false [IO.File]::WriteAllLines($fullPath, $csvLines, $utf8WithoutBom) Write-Host ('Saved Autopilot CSV: {0}' -f $fullPath) return $fullPath } function Test-AutopilotGraphAccess { [CmdletBinding()] param() # Test the exact collection used by the import POST, without creating a device. $uri = $script:GraphBaseUri + '/v1.0/deviceManagement/importedWindowsAutopilotDeviceIdentities?$top=1&$select=id,serialNumber' try { $null = Invoke-CustomGraphRequest -Method GET -Uri $uri Write-Host ('Intune Autopilot import preflight passed for {0}.' -f $script:GraphContext.Account) } catch { $statusCode = [int] $_.Exception.Data['StatusCode'] if ($statusCode -eq 403) { throw ('Intune returned HTTP 403 during the import preflight. Signed-in account: {0}; client ID: {1}; token scopes: {2}. Authentication through the dedicated app succeeded, but Intune did not authorize the imported-device collection. No PIM role is activated by this script.' -f $script:GraphContext.Account, $script:GraphContext.ClientId, ($script:GraphContext.Scopes -join ', ')) } throw } } function New-AutopilotImportedDevice { [CmdletBinding()] param( [Parameter(Mandatory = $true)] [object] $Record ) $body = [ordered]@{ '@odata.type' = '#microsoft.graph.importedWindowsAutopilotDeviceIdentity' groupTag = [string] $Record.'Group Tag' serialNumber = [string] $Record.'Device Serial Number' productKey = [string] $Record.'Windows Product ID' importId = [Guid]::NewGuid().ToString() hardwareIdentifier = [string] $Record.'Hardware Hash' state = [ordered]@{ '@odata.type' = 'microsoft.graph.importedWindowsAutopilotDeviceIdentityState' deviceImportStatus = 'pending' deviceRegistrationId = '' deviceErrorCode = 0 deviceErrorName = '' } assignedUserPrincipalName = [string] $Record.'Assigned User' } $uri = $script:GraphBaseUri + '/v1.0/deviceManagement/importedWindowsAutopilotDeviceIdentities' $response = Invoke-CustomGraphRequest -Method POST -Uri $uri -Body $body if ($null -eq $response -or [string]::IsNullOrWhiteSpace([string] $response.id)) { throw ('Microsoft Graph accepted no usable import object for serial number {0}.' -f $Record.'Device Serial Number') } Write-Host ('Submitted serial {0} to Windows Autopilot. Import object ID: {1}' -f $Record.'Device Serial Number', $response.id) return $response } function Wait-AutopilotImports { [CmdletBinding()] param( [Parameter(Mandatory = $true)] [object[]] $SubmittedImports, [Parameter(Mandatory = $true)] [int] $TimeoutMinutes, [Parameter(Mandatory = $true)] [int] $PollSeconds ) $deadline = (Get-Date).AddMinutes($TimeoutMinutes) $lastStatus = @{} $currentById = @{} while ($true) { $processingCount = 0 foreach ($submitted in $SubmittedImports) { $uri = '{0}/v1.0/deviceManagement/importedWindowsAutopilotDeviceIdentities/{1}' -f $script:GraphBaseUri, $submitted.id $current = Invoke-CustomGraphRequest -Method GET -Uri $uri if ($null -eq $current.id -and $null -ne $current.value) { $current = @($current.value)[0] } $currentById[[string] $submitted.id] = $current $status = 'unknown' if ($null -ne $current.state -and -not [string]::IsNullOrWhiteSpace([string] $current.state.deviceImportStatus)) { $status = [string] $current.state.deviceImportStatus } if ($lastStatus[[string] $submitted.id] -ne $status) { Write-Host ('{0}: import status {1}; error code {2}; error name {3}' -f $current.serialNumber, $status, $current.state.deviceErrorCode, $current.state.deviceErrorName) $lastStatus[[string] $submitted.id] = $status } if ($status -notin @('complete', 'error')) { $processingCount++ } } if ($processingCount -eq 0) { break } if ((Get-Date) -ge $deadline) { throw ('Timed out after {0} minute(s) while waiting for {1} Autopilot import(s) to finish.' -f $TimeoutMinutes, $processingCount) } Write-Host ('Waiting for {0} of {1} Autopilot import(s) to finish.' -f $processingCount, $SubmittedImports.Count) Start-Sleep -Seconds $PollSeconds } $results = @() foreach ($submitted in $SubmittedImports) { $results += $currentById[[string] $submitted.id] } $failed = @($results | Where-Object { $_.state.deviceImportStatus -eq 'error' }) foreach ($failure in $failed) { Write-Warning ('Autopilot import failed for serial {0}. Error code: {1}; error name: {2}' -f $failure.serialNumber, $failure.state.deviceErrorCode, $failure.state.deviceErrorName) } if ($failed.Count -gt 0) { throw ('{0} Autopilot import(s) failed.' -f $failed.Count) } $complete = @($results | Where-Object { $_.state.deviceImportStatus -eq 'complete' }) Write-Host ('{0} device(s) imported successfully.' -f $complete.Count) return $results } function Wait-AutopilotDeviceSynchronization { [CmdletBinding()] param( [Parameter(Mandatory = $true)] [object[]] $CompletedImports, [Parameter(Mandatory = $true)] [int] $TimeoutMinutes, [Parameter(Mandatory = $true)] [int] $PollSeconds ) $deadline = (Get-Date).AddMinutes($TimeoutMinutes) $devicesById = @{} while ($true) { $processingCount = 0 foreach ($import in $CompletedImports) { $registrationId = [string] $import.state.deviceRegistrationId if ([string]::IsNullOrWhiteSpace($registrationId)) { throw ('The completed import for serial {0} has no deviceRegistrationId.' -f $import.serialNumber) } try { $uri = '{0}/v1.0/deviceManagement/windowsAutopilotDeviceIdentities/{1}' -f $script:GraphBaseUri, $registrationId $device = Invoke-CustomGraphRequest -Method GET -Uri $uri if ($null -eq $device.id -and $null -ne $device.value) { $device = @($device.value)[0] } if ($null -ne $device -and -not [string]::IsNullOrWhiteSpace([string] $device.id)) { $devicesById[$registrationId] = $device } else { $processingCount++ } } catch { $statusCode = [int] $_.Exception.Data['StatusCode'] if ($statusCode -eq 404) { $processingCount++ } else { throw } } } if ($processingCount -eq 0) { break } if ((Get-Date) -ge $deadline) { throw ('Timed out after {0} minute(s) while waiting for {1} imported device(s) to appear in the Autopilot device inventory.' -f $TimeoutMinutes, $processingCount) } Write-Host ('Waiting for {0} of {1} device(s) to synchronize into the Autopilot device inventory.' -f $processingCount, $CompletedImports.Count) Start-Sleep -Seconds $PollSeconds } $devices = @() foreach ($import in $CompletedImports) { $devices += $devicesById[[string] $import.state.deviceRegistrationId] } Write-Host 'All imported devices are visible in the Windows Autopilot device inventory.' return $devices } function Set-AutopilotComputerName { [CmdletBinding()] param( [Parameter(Mandatory = $true)] [object[]] $AutopilotDevices, [Parameter(Mandatory = $true)] [string] $ComputerName ) foreach ($device in $AutopilotDevices) { $uri = '{0}/v1.0/deviceManagement/windowsAutopilotDeviceIdentities/{1}/updateDeviceProperties' -f $script:GraphBaseUri, $device.id $null = Invoke-CustomGraphRequest -Method POST -Uri $uri -Body @{ displayName = $ComputerName } Write-Host ('Assigned Autopilot computer name {0} to serial {1}.' -f $ComputerName, $device.serialNumber) } } function Get-TargetSecurityGroup { [CmdletBinding()] param( [Parameter(Mandatory = $false)] [string] $DisplayName, [Parameter(Mandatory = $false)] [string] $GroupId ) if (-not [string]::IsNullOrWhiteSpace($GroupId)) { $uri = '{0}/v1.0/groups/{1}?$select=id,displayName,securityEnabled,isAssignableToRole' -f $script:GraphBaseUri, $GroupId $group = Invoke-CustomGraphRequest -Method GET -Uri $uri } else { $escapedName = $DisplayName.Replace("'", "''") $filter = [Uri]::EscapeDataString("displayName eq '$escapedName'") $uri = $script:GraphBaseUri + '/v1.0/groups?$filter=' + $filter + '&$select=id,displayName,securityEnabled,isAssignableToRole' $response = Invoke-CustomGraphRequest -Method GET -Uri $uri -AdditionalHeaders @{ ConsistencyLevel = 'eventual' } $matches = @($response.value) if ($matches.Count -eq 0) { throw ('No Microsoft Entra group was found with display name {0}.' -f $DisplayName) } if ($matches.Count -gt 1) { throw ('More than one Microsoft Entra group has display name {0}. Use -AddToGroupId to select the exact group.' -f $DisplayName) } $group = $matches[0] } if (-not [bool] $group.securityEnabled) { throw ('Group {0} is not a security group. Devices can be added only to security groups.' -f $group.displayName) } if ([bool] $group.isAssignableToRole) { throw ('Group {0} is role-assignable. This script intentionally does not request RoleManagement.ReadWrite.Directory.' -f $group.displayName) } return $group } function Wait-EntraDeviceObject { [CmdletBinding()] param( [Parameter(Mandatory = $true)] [string] $AutopilotDeviceId, [Parameter(Mandatory = $true)] [string] $SerialNumber, [Parameter(Mandatory = $true)] [int] $TimeoutMinutes, [Parameter(Mandatory = $true)] [int] $PollSeconds ) $deadline = (Get-Date).AddMinutes($TimeoutMinutes) while ((Get-Date) -lt $deadline) { $autopilotUri = '{0}/v1.0/deviceManagement/windowsAutopilotDeviceIdentities/{1}' -f $script:GraphBaseUri, $AutopilotDeviceId $autopilotDevice = Invoke-CustomGraphRequest -Method GET -Uri $autopilotUri if ($null -eq $autopilotDevice.id -and $null -ne $autopilotDevice.value) { $autopilotDevice = @($autopilotDevice.value)[0] } $entraDeviceId = [string] $autopilotDevice.azureActiveDirectoryDeviceId if (-not [string]::IsNullOrWhiteSpace($entraDeviceId) -and $entraDeviceId -ne '00000000-0000-0000-0000-000000000000') { $filter = [Uri]::EscapeDataString("deviceId eq '$entraDeviceId'") $deviceUri = $script:GraphBaseUri + '/v1.0/devices?$filter=' + $filter + '&$select=id,deviceId,displayName' $response = Invoke-CustomGraphRequest -Method GET -Uri $deviceUri -AdditionalHeaders @{ ConsistencyLevel = 'eventual' } $devices = @($response.value) if ($devices.Count -eq 1) { return $devices[0] } if ($devices.Count -gt 1) { throw ('More than one Entra device object matched deviceId {0} for serial {1}.' -f $entraDeviceId, $SerialNumber) } } Write-Host ('Waiting for the Microsoft Entra device object for serial {0}.' -f $SerialNumber) Start-Sleep -Seconds $PollSeconds } throw ('Timed out after {0} minute(s) waiting for a Microsoft Entra device object for serial {1}.' -f $TimeoutMinutes, $SerialNumber) } function Add-AutopilotDevicesToGroup { [CmdletBinding()] param( [Parameter(Mandatory = $true)] [object[]] $AutopilotDevices, [Parameter(Mandatory = $true)] [object] $Group, [Parameter(Mandatory = $true)] [int] $TimeoutMinutes, [Parameter(Mandatory = $true)] [int] $PollSeconds ) foreach ($autopilotDevice in $AutopilotDevices) { $entraDevice = Wait-EntraDeviceObject -AutopilotDeviceId ([string] $autopilotDevice.id) -SerialNumber ([string] $autopilotDevice.serialNumber) -TimeoutMinutes $TimeoutMinutes -PollSeconds $PollSeconds $uri = ('{0}/v1.0/groups/{1}/members/' -f $script:GraphBaseUri, $Group.id) + '$ref' $body = @{ '@odata.id' = '{0}/v1.0/directoryObjects/{1}' -f $script:GraphBaseUri, $entraDevice.id } try { $null = Invoke-CustomGraphRequest -Method POST -Uri $uri -Body $body Write-Host ('Added serial {0} to group {1} ({2}).' -f $autopilotDevice.serialNumber, $Group.displayName, $Group.id) } catch { $statusCode = [int] $_.Exception.Data['StatusCode'] $graphMessage = [string] $_.Exception.Data['GraphMessage'] if ($statusCode -eq 400 -and $graphMessage -match 'already exist') { Write-Host ('Serial {0} is already a member of group {1}.' -f $autopilotDevice.serialNumber, $Group.displayName) continue } if ($statusCode -eq 403) { throw ('Microsoft Entra returned HTTP 403 while adding serial {0} to group {1}. The application token contains group scopes, but the signed-in user must also have effective authority to update that group. No role checkout is performed by this script.' -f $autopilotDevice.serialNumber, $Group.displayName) } throw } } } function Wait-AutopilotProfileAssignment { [CmdletBinding()] param( [Parameter(Mandatory = $true)] [object[]] $AutopilotDevices, [Parameter(Mandatory = $true)] [int] $TimeoutMinutes, [Parameter(Mandatory = $true)] [int] $PollSeconds ) $deadline = (Get-Date).AddMinutes($TimeoutMinutes) $lastStatus = @{} while ($true) { $processingCount = 0 foreach ($device in $AutopilotDevices) { $uri = '{0}/beta/deviceManagement/windowsAutopilotDeviceIdentities/{1}?$select=id,serialNumber,deploymentProfileAssignmentStatus' -f $script:GraphBaseUri, $device.id $current = Invoke-CustomGraphRequest -Method GET -Uri $uri if ($null -eq $current.id -and $null -ne $current.value) { $current = @($current.value)[0] } $status = [string] $current.deploymentProfileAssignmentStatus if ([string]::IsNullOrWhiteSpace($status)) { $status = 'unknown' } if ($lastStatus[[string] $device.id] -ne $status) { Write-Host ('{0}: deployment profile assignment status {1}' -f $device.serialNumber, $status) $lastStatus[[string] $device.id] = $status } if ($status -eq 'failed') { throw ('Deployment profile assignment failed for serial {0}.' -f $device.serialNumber) } if (-not $status.StartsWith('assigned', [StringComparison]::OrdinalIgnoreCase)) { $processingCount++ } } if ($processingCount -eq 0) { Write-Host 'Deployment profiles are assigned to all imported devices.' return } if ((Get-Date) -ge $deadline) { throw ('Timed out after {0} minute(s) while waiting for {1} deployment profile assignment(s).' -f $TimeoutMinutes, $processingCount) } Write-Host ('Waiting for {0} of {1} deployment profile assignment(s).' -f $processingCount, $AutopilotDevices.Count) Start-Sleep -Seconds $PollSeconds } } # NOTE (v4.4.0): Run -Online -Email user@yourdomain.com to discover the tenant. # Tenant discovery is a domain hint only; the authenticated Graph context is checked. # The application must be registered in that same tenant and have delegated permissions. # Main execution $workplaceJoinState = $null $shouldReboot = $false $records = @() try { if ($Online) { if ($Partner) { throw '-Partner cannot be combined with -Online.' } if ($Reboot -and -not $Assign) { throw '-Reboot requires -Assign.' } if (-not [string]::IsNullOrWhiteSpace($AddToGroup) -and -not [string]::IsNullOrWhiteSpace($AddToGroupId)) { throw 'Specify either -AddToGroup or -AddToGroupId, not both.' } if (-not [string]::IsNullOrWhiteSpace($AddToGroupId) -and -not (Test-GuidValue -Value $AddToGroupId)) { throw ('AddToGroupId must be a GUID. Received: {0}' -f $AddToGroupId) } if (-not [string]::IsNullOrWhiteSpace($AssignedComputerName)) { if ($AssignedComputerName.Length -gt 15) { throw '-AssignedComputerName cannot exceed 15 characters.' } if ($Name.Count -gt 1) { throw '-AssignedComputerName can be used only when importing one device per run.' } } # Email-based discovery does not sign in or use the Graph Command Line Tools app. # This fixed client is a SINGLE-TENANT application; the discovered tenant must be its home tenant. if (-not [string]::IsNullOrWhiteSpace($TenantId)) { throw 'Do not supply -TenantId. HashUP discovers the tenant from -Email.' } $ClientId = '03269948-b9c1-441a-ab03-14dfa338e044' if ([string]::IsNullOrWhiteSpace($Email)) { $Email = Read-Host 'Enter your organizational email address' } $TenantId = Get-TenantFromEmail -Address $Email Write-Host 'Tenant discovered from organizational email domain.' if (-not $PSBoundParameters.ContainsKey('GroupTag')) { $GroupTag = Read-GroupTag } # Apply the OOBE Workplace Join safeguard before loading modules or starting sign-in. $workplaceJoinState = Enable-TemporaryWorkplaceJoinBlock Initialize-GraphAuthenticationModule } foreach ($computer in $Name) { $records += Get-AutopilotHardwareRecord -ComputerName $computer -Credential $Credential -Partner:$Partner -Force:$Force -GroupTag $GroupTag -AssignedUser $AssignedUser } if ($records.Count -eq 0) { throw 'No Autopilot hardware records were collected.' } if (-not [string]::IsNullOrWhiteSpace($OutputFile)) { $null = Write-AutopilotCsv -Records $records -Path $OutputFile -Append:$Append -Partner:$Partner -GroupTag $GroupTag -AssignedUser $AssignedUser } if (-not $Online) { if ([string]::IsNullOrWhiteSpace($OutputFile)) { if ($Partner) { $records | Select-Object 'Device Serial Number', 'Windows Product ID', 'Hardware Hash', 'Manufacturer name', 'Device model' } elseif (-not [string]::IsNullOrWhiteSpace($AssignedUser)) { $records | Select-Object 'Device Serial Number', 'Windows Product ID', 'Hardware Hash', 'Group Tag', 'Assigned User' } elseif (-not [string]::IsNullOrWhiteSpace($GroupTag)) { $records | Select-Object 'Device Serial Number', 'Windows Product ID', 'Hardware Hash', 'Group Tag' } else { $records | Select-Object 'Device Serial Number', 'Windows Product ID', 'Hardware Hash' } } return } $requiredScopes = @('DeviceManagementServiceConfig.ReadWrite.All') foreach ($scope in $Scopes) { if (-not [string]::IsNullOrWhiteSpace($scope) -and $requiredScopes -notcontains $scope) { $requiredScopes += $scope } } $groupOperationRequested = ( -not [string]::IsNullOrWhiteSpace($AddToGroup) -or -not [string]::IsNullOrWhiteSpace($AddToGroupId) ) if ($groupOperationRequested) { foreach ($scope in @('Group.ReadWrite.All', 'GroupMember.ReadWrite.All', 'Device.Read.All')) { if ($requiredScopes -notcontains $scope) { $requiredScopes += $scope } } } Connect-AutopilotGraph -TenantId $TenantId -ClientId $ClientId -RequiredScopes $requiredScopes -UseDeviceCode:$UseDeviceCode Test-AutopilotGraphAccess $submittedImports = @() foreach ($record in $records) { $submittedImports += New-AutopilotImportedDevice -Record $record } $completedImports = @(Wait-AutopilotImports -SubmittedImports $submittedImports -TimeoutMinutes $ImportTimeoutMinutes -PollSeconds $PollSeconds) $autopilotDevices = @(Wait-AutopilotDeviceSynchronization -CompletedImports $completedImports -TimeoutMinutes $SyncTimeoutMinutes -PollSeconds $PollSeconds) if (-not [string]::IsNullOrWhiteSpace($AssignedComputerName)) { Set-AutopilotComputerName -AutopilotDevices $autopilotDevices -ComputerName $AssignedComputerName } if ($groupOperationRequested) { $group = Get-TargetSecurityGroup -DisplayName $AddToGroup -GroupId $AddToGroupId Add-AutopilotDevicesToGroup -AutopilotDevices $autopilotDevices -Group $group -TimeoutMinutes $SyncTimeoutMinutes -PollSeconds $PollSeconds } if ($Assign) { Wait-AutopilotProfileAssignment -AutopilotDevices $autopilotDevices -TimeoutMinutes $AssignmentTimeoutMinutes -PollSeconds $PollSeconds if ($Reboot) { $shouldReboot = $true } } Write-Host '' Write-Host ('Completed successfully for {0} device(s).' -f $autopilotDevices.Count) } finally { if ($script:GraphConnected) { try { Microsoft.Graph.Authentication\Disconnect-MgGraph -ErrorAction SilentlyContinue | Out-Null } catch { } $script:GraphConnected = $false $script:GraphContext = $null } if ($null -ne $workplaceJoinState) { if ($KeepWorkplaceJoinBlock) { Write-Host 'Keeping BlockAADWorkplaceJoin=1 because -KeepWorkplaceJoinBlock was specified.' } else { Restore-WorkplaceJoinBlock -State $workplaceJoinState } } } if ($shouldReboot) { Restart-Computer -Force } |