Featured image of post Automating with PowerShell: Automating intune Autopilot configuration

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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
########################## 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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
########################## 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

All blogs are posted under AGPL3.0 unless stated otherwise
comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy