Automating with PowerShell: Automating intune Autopilot configuration

So yesterday I was watching a webinar about intune and Autopilot. Autopilot is pretty cool for MSPs because it becomes fairly simple to give users a nice OOBE. It also makes setup for devices a lot less of a hassle, the only issue that was spoken about during the webinar is that there is still a lot of manual clicking.

This is why I took it upon myself to create some automation scripts for AutoPilot. We’re using the Graph API so you’ll need to setup your Secure Application Model before you can use these scripts. You’ll also need to perform the following steps to add a permission to the application:

  • Go to the Azure Portal.
  • Click on Azure Active Directory, now click on “App Registrations”.
  • Find your Secure App Model application. You can search based on the ApplicationID.
  • Go to “API Permissions” and click Add a permission.
  • Choose “Microsoft Graph” and “Application permission”.
  • Search for “Reports” and click on “DeviceManagementServiceConfig.ReadWrite.All”. Click on add permission
  • Do the same for “Delegate Permissions”.
  • Finally, click on “Grant Admin Consent for Company Name.

Importing Device ID’s for autopilot

So one of the first things I noticed is that engineers are still entering device ID’s manually, or uploading CSV files by logging into the portal, etc. That seems like a bit of an hassle to me, so for that you can use the following script.

First you’ll have to create your import CSV file, Most of the time this can be downloaded from your supplier, or requested. When you have this file, execute the script.

########################## Office 365 ############################
$ApplicationId = 'YourApplicationID'
$ApplicationSecret = 'SecretApplicationSecret' | Convertto-SecureString -AsPlainText -Force
$TenantID = 'YourTenantID'
$RefreshToken = 'SuperSecretRefreshToken'
$upn = 'UPN-Used-To-Generate-Tokens'
$CustomerTenantID = "YOURCLIENTSTENANT.onmicrosoft.com"
$CSVFilePath = "C:\Temp\Import-CSV-YourClientsTenant.txt"
########################## Office 365 ############################
$credential = New-Object System.Management.Automation.PSCredential($ApplicationId, $ApplicationSecret)
write-host "Generating token to log into Intune" -ForegroundColor Green
$graphToken = New-PartnerAccessToken -ApplicationId $ApplicationId -Credential $credential -RefreshToken $refreshToken -Scopes 'https://graph.microsoft.com/.default' -ServicePrincipal -Tenant $CustomerTenantID
$Header = @{
    Authorization = "Bearer $($graphToken.AccessToken)"
}
write-host "Importing CSV File." -ForegroundColor Green
$CsvFile = Import-Csv $CSVFilePath -Delimiter ","
#$RandGuid = [guid]::NewGuid()
foreach ($Line in $CsvFile) {
    $intuneBody = @{
        orderIdentifier    = "CyberDrain.com Import Script"
        serialNumber       = $line.'Device Serial Number'
        productKey         = $line.'Windows Product ID'
        hardwareIdentifier = $Line.'Hardware Hash'
        state              = @{
            deviceImportStatus   = 'Complete'
            deviceRegistrationId = '1'
            deviceErrorCode      = '15'
            deviceErrorName      = "No Errors Detected"
        }
    } | ConvertTo-Json

    $InTuneDevicesURI = "https://graph.microsoft.com/beta/deviceManagement/importedWindowsAutopilotDeviceIdentities"
    Invoke-RestMethod -Uri $InTuneDevicesURI -Headers $Header -body $intuneBody -Method POST -ContentType "application/json"

}

After executing this script, it’ll appear in your client’s intune portal like this. This can take some time sometimes because of the Sync on the Microsoft side. You can force this by hitting the “Sync” button.

You could easily automate this script to run on a schedule, and just replace the CSV file whenever you want. That way you import your devices with zero-touch.

Adding a Windows Deployment Autopilot Profile

One of the annoying repetitive tasks when you start setting up Autopilot is the Autopilot profile. This script will automate that for you and set the settings to your wishes. I don’t directly apply the profile, because sometimes you just want to make some tiny edits per client before applying.

########################## Office 365 ############################
$ApplicationId = 'YourApplicationID'
$ApplicationSecret = 'SecretApplicationSecret' | Convertto-SecureString -AsPlainText -Force
$TenantID = 'YourTenantID'
$RefreshToken = 'SuperSecretRefreshToken'
$upn = 'UPN-Used-To-Generate-Tokens'
$CustomerTenantID = "YOURCLIENTSTENANT.onmicrosoft.com"
########################## Office 365 ############################
$credential = New-Object System.Management.Automation.PSCredential($ApplicationId, $ApplicationSecret)
write-host "Generating token to log into Intune" -ForegroundColor Green
$graphToken = New-PartnerAccessToken -ApplicationId $ApplicationId -Credential $credential -RefreshToken $refreshToken -Scopes 'https://graph.microsoft.com/.default' -ServicePrincipal -Tenant $CustomerTenantID
$Header = @{
    Authorization = "Bearer $($graphToken.AccessToken)"
}
write-host "Creating Deployment Profile" -ForegroundColor Green

$intuneBody = @{
    "@odata.type"                          = "#microsoft.graph.activeDirectoryWindowsAutopilotDeploymentProfile"
    displayName                            = "CyberDrain.com Default Profile"
    description                            = "This deployment profile has been created by the CyberDrain.com Profile Deployment script"
    language                               = 'EN'
    hybridAzureADJoinSkipConnectivityCheck = $true
    extractHardwareHash                    = $true
    enableWhiteGlove                       = $true
    outOfBoxExperienceSettings             = @{
        "@odata.type"             = "microsoft.graph.outOfBoxExperienceSettings"
        hidePrivacySettings       = $true
        hideEULA                  = $true
        userType                  = 'Standard'
        deviceUsageType           = 'Shared'
        skipKeyboardSelectionPage = $true
        hideEscapeLink            = $true
    }
    enrollmentStatusScreenSettings         = @{
        '@odata.type'                                    = "microsoft.graph.windowsEnrollmentStatusScreenSettings"
        hideInstallationProgress                         = $true
        allowDeviceUseBeforeProfileAndAppInstallComplete = $true
        blockDeviceSetupRetryByUser                      = $false
        allowLogCollectionOnInstallFailure               = $true
        customErrorMessage                               = "An error has occured. Please contact your IT Administrator"
        installProgressTimeoutInMinutes                  = "15"
        allowDeviceUseOnInstallFailure                   = $true
    }
} | ConvertTo-Json

$InTuneProfileURI = "https://graph.microsoft.com/beta/deviceManagement/windowsAutopilotDeploymentProfiles"
Invoke-RestMethod -Uri $InTuneProfileURI -Headers $Header -body $intuneBody -Method POST -ContentType "application/json"

And that’s it! Maybe I’ll focus on creating applications via PowerShell and assigning them next time. If you have any requests, let me know!

As always, Happy PowerShelling

4 thoughts on “Automating with PowerShell: Automating intune Autopilot configuration

  1. Ivan

    Have you tried this as a straight Graph API query with the Graph Explorer?

    As that is where I have been experimenting with for these Autopilot controls. It always returns an error relating to JSON format each time I try any sort of operation involving a write action.

    I’m logged in as Global Admin and am finding it extremely frustrating.

    Reply
    1. Kelvin Tegelaar Post author

      You’ll have to make sure the JSON is valid via a JSON Validator, I’ve often forgotten commas or minor other things that validators help with.

      Another one that could help is changing the endpoint. To use these cmdlets you’ll need to change the graph endpoint from version v1.0 to beta. 🙂

      Reply
  2. Patrick

    Hi Kevin,

    Have you ever looked in too github to place your script. So there are no errors in copy/past from the scripts you make.

    Reply
    1. Kelvin Tegelaar Post author

      I have, but I don’t really like the sort of obligation to maintain two locations, I also don’t want to contribute to yet another abandoned repo if I ever decide to stop updating something 🙂

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.