How to use PowerShell to access Microsoft Intune via Microsoft Graph API?

In earlier blogs we have had an introduction to Microsoft Graph and what we can do with Microsoft Intune via the Microsoft Graph API. In this blog I want to add PowerShell to the story and show what we need to use PowerShell to access Microsoft Intune via the Microsoft Graph API. As you may have found out there are currently no default cmdlets available to use to use with Microsoft Intune, but we can use PowerShell to “execute” REST API calls to manage Microsoft Intune.

What do we need?

To be able to communicate from PowerShell with Microsoft Intune via the Microsoft Graph API, Microsoft created an Azure AD Enterprise App which can be used. This Azure AD Enterprise App is called Microsoft Intune and available in every Azure AD tenant.

Microsoft Intune PowerShell app in Azure AD

By using the “out of the box” Microsoft Intune PowerShell app you do not have to set any permissions to get access to Microosft Intune via the Microsoft Graph API. You can however create a custom Enterprise App in Azure AD to access Microsoft Intune and possible other resources. Some great blogs about this can be found here and here.

The scripts from Dave Falkus on GitHub are all using the default Microsoft Intune PowerShell app in Azure AD, so you do not need to alter the scripts if you use the default app.

When setting up a connection with the Microsoft Intune PowerShell App in Azure AD, we need to authenticate via Modern Authentication. oAuth is used to authenticate and maintain the connection between, in this case the PowerShell session and Microsoft Intune via the Graph API.

After the authentication is done, you can use PowerShell to invoke REST API calls to the Microsoft Graph API like we also did in the Graph Explorer, but now you can use the results in for instance a variable in PowerShell.

To be able to access the Microsoft Intune PowerShell app in Azure AD you need to intstall the Azure AD PowerShell modules to be able to have access to the Azure AD related cmdlets. Getting the latest Azure AD PowerShell modules can be done as follows;

  1. Open PowerShell in Administrator mode
  2. Click Install-Module AzureAD
  3. Click Y to download the module from the repository

While working with PowerShell I noticed that the PowerShell ISE in Windows 10 is not ideal to be used while coding scripts. Peers in the community guided me to Visual Studio Code with the PowerShell extensions.

How to setup a connection?

Luckily the Intune Product Group has posted samples on Github and documented the steps how to authenticate to the Microsoft Graph so that you can use REST API call to manage Microsoft Intune. After you have downloaded the examples from GutHub, open any script from the repository. Every script has common code to take care of the authentication to Microsoft Intune via Microsoft Graph.

Every script of that are in the Microsoft Intune GitHub repository is build the same and has two sections available. One function called Get-AuthToken and a part this is called authentication region.

If we look at the function Get-AuthToken the following sections:

$userUpn = New-Object "System.Net.Mail.MailAddress" -ArgumentList $User
$tenant = $userUpn.Host

In this section the variable $User which is a required parameter of the function Get-AuthToken is transformed in an MailAddress object. This way the host value of this object can be easily passed on to the $tenant variable.

The next section of the function is the part that takes care of checking if the AzureAD PowerShell module is installed on the workstation you are using. The script will be exited when the AzureAD PowerShell module is not present.

$AadModule = Get-Module -Name "AzureAD" -ListAvailable
if ($AadModule -eq $null) {

Write-Host "AzureAD PowerShell module not found, looking for AzureADPreview"

$AadModule = Get-Module -Name "AzureADPreview" -ListAvailable
}

if ($AadModule -eq $null) {
write-host
write-host "AzureAD Powershell module not installed..." -f Red
write-host "Install by running 'Install-Module AzureAD' or 'Install-Module AzureADPreview' from an elevated PowerShell prompt" -f Yellow
write-host "Script can't continue..." -f Red
write-host
exit
}

# Getting path to ActiveDirectory Assemblies
# If the module count is greater than 1 find the latest version

if($AadModule.count -gt 1){
$Latest_Version = ($AadModule | select version | Sort-Object)[-1]

$aadModule = $AadModule | ? { $_.version -eq $Latest_Version.version }

# Checking if there are multiple versions of the same module found

if($AadModule.count -gt 1){

$aadModule = $AadModule | select -Unique

}

$adal = Join-Path $AadModule.ModuleBase "Microsoft.IdentityModel.Clients.ActiveDirectory.dll"

$adalforms = Join-Path $AadModule.ModuleBase "Microsoft.IdentityModel.Clients.ActiveDirectory.Platform.dll"

}

else {

$adal = Join-Path $AadModule.ModuleBase "Microsoft.IdentityModel.Clients.ActiveDirectory.dll"

$adalforms = Join-Path $AadModule.ModuleBase "Microsoft.IdentityModel.Clients.ActiveDirectory.Platform.dll"
}

It could be the case that multiple versions of the AzureAD modules are installed on the workstation, if that is true the script will detect the latest version ($Latest_Version) and use this one to authenticate to the Microsoft Graph API using Azure AD.

[System.Reflection.Assembly]::LoadFrom($adal) | Out-Null

[System.Reflection.Assembly]::LoadFrom($adalforms) | Out-Null

$clientId = "d1ddf0e4-d672-4dae-b554-9d5bdfd93547"

$redirectUri = "urn:ietf:wg:oauth:2.0:oob"

$resourceAppIdURI = "https://graph.microsoft.com"

$authority = "https://login.microsoftonline.com/$Tenant"

The sectrion above is the configuration of the connection, the value of the $clientId variable is the ID of the Microsoft Intune PowerShell app in Azure AD. So if you descide to use a custom one, you need to alter this value to the Application ID value of your app in Azure AD.

The RedirectUri (urn:ietf:wg:oauth:2.0:oob) is used to signal Azure AD to return the authorization code. The redirect_uri of the app, is where authentication responses can be sent and received by the app. Read more on OAuth 2.0 authorization flow and Azure AD here.

try {
$authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority

$platformParameters = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.PlatformParameters" -ArgumentList "Auto"

$userId = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifier" -ArgumentList ($User, "OptionalDisplayableId")

$authResult = $authContext.AcquireTokenAsync($resourceAppIdURI,$clientId,$redirectUri,$platformParameters,$userId).Result

if($authResult.AccessToken){
# Creating header for Authorization token
$authHeader = @{
'Content-Type'='application/json'
'Authorization'="Bearer " + $authResult.AccessToken
'ExpiresOn'=$authResult.ExpiresOn
}

return $authHeader
}
else {
Write-Host
Write-Host "Authorization Access Token is null, please re-run authentication..." -ForegroundColor Red
Write-Host
break
}
}

catch {
write-host $_.Exception.Message -f Red
write-host $_.Exception.ItemName -f Red
write-host
break
}
}

The above section is there part with the following brings all together and prompts the user with a sign in prompt to authenticate with the global admin to Azure AD.

$authResult = $authContext.AcquireTokenAsync($resourceAppIdURI,$clientId,$redirectUri,$platformParameters,$userId).Result

Depending on if setting up the connection and results of authenticating via oAuth2 an error is presented or not.

After authenticating the authentication token is used in a global variable called authToken, this authToken variable can be used by other functions or while invoking a REST API call in the script.

# Getting the authorization token
$global:authToken = Get-AuthToken -User $User
}
#endregion

When looking at the $authToken variable, the authentication token and the expiry date of the token are shared.

After setting up a successful connection to you are able to invoke REST calls to the Microsoft Graph API to get information or perform actions in Microsoft Intune, but more on that in my next blog about the Microsoft Graph API and Microsoft Intune.

More information can be found here:

Comments

Total
0
Shares
Leave a Reply

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

Previous Post

So, what can we do with Microsoft Intune via Microsoft Graph API?

Next Post

Happy New (Enterprise Mobility / ConfigMgr) Year!

Related Posts
Total
0
Share