|

Clearing Azure AD Device Attribute Using PowerShell Script: A Step-by-Step Guide

Introduction

In today’s digital landscape, managing and maintaining a robust directory of devices is essential for organizations of all sizes. Microsoft Azure Active Directory (Azure AD) offers a powerful set of tools and functionalities to help manage devices effectively. However, at times, you may encounter situations where you need to clear specific attributes associated with devices in your Azure AD environment. In this blog post, we will explore how to accomplish this task using a PowerShell script that runs in the console and provides information to the user.

Understanding Azure AD Device Attributes

Azure AD stores a range of attributes for each device object. These attributes provide valuable information about devices, such as device name, operating system, device ID, and more. Occasionally, you might encounter scenarios where you need to clear certain attributes associated with a device, such as the description or custom properties. With PowerShell, you can easily automate this process and streamline your device management tasks.

PowerShell Script to Clear Azure AD Device Attribute

Before we dive into the script, it’s important to note that this example assumes you have the necessary permissions and have connected to Azure AD using the appropriate PowerShell modules. Now, let’s take a look at the PowerShell script that runs in the console and provides information to the user:

PowerShell
#requires -version 4
<#
.SYNOPSIS
  Script to remove an entry from an ExtensionAttribute on a Device in Azure AD
.DESCRIPTION
  This Script removes the entry in the defined extensionAttribute on a Device Object in Azure AD.
  It is a console script, which means that you have to run it from a powershell console to see the output.
.PARAMETER 
    none
.INPUTS
    DeviceId from AzureAd
    This Parameter will be queried in the console
.OUTPUTS
  yes/no
  Output will be shown in the console.
.NOTES
  Version:        1.0
  Author:         LosFla (http://www.losfla.com/)
  Creation Date:  2023/06/05
  Purpose/Change: Initial script development
  
.EXAMPLE
  .\Clear-ExtensionAttributeOnAadDevice.ps1
#>

#region variables
$ExtensionAttributeName = 'ExtensionAttribute1' # Name of the ExtensionAttribute you want to clear

#endregion


function Set-AadDeviceExtensionAttribute
{
    [CmdletBinding()]
    param(
        [Parameter(Position=2,mandatory=$true)]
        $AzureAdDevice,
        [Parameter(Position=0,mandatory=$true)]
        [string] $ExtensionAttributeName,
        [Parameter(Position=1,mandatory=$false)]
        $ExtensionAttributeValue = $null
        
    )

    # write ExtensionAttribute to Azure AD
    $uri = $null
    $uri = "https://graph.microsoft.com/beta/devices/$($AzureAdDevice.id)"

    $json = @{
        "extensionAttributes" = @{
            $($ExtensionAttributeName) = $ExtensionAttributeValue
        }
    } | ConvertTo-Json

    try{
        Invoke-MgGraphRequest -Uri $uri -Body $json -Method PATCH -ContentType "application/json"
        
    }
    catch{
        throw $_
    }
}

# 1. User Input Validation
$RegexObjectId = "[A-Za-z0-9]+-[A-Za-z0-9]+-[A-Za-z0-9]+-[A-Za-z0-9]+-[A-Za-z0-9]"

# DeviceId
$DeviceId = Read-Host "Please enter the objectId of the device you want to clear (You can retrieve it from AzureAd)"

if(!($DeviceId -match $RegexObjectId)){
    
    Write-Host "input doesn't match the expected ObjectId format" -ForegroundColor Red
    Write-Host "Hint: please enter the ObjectId in the following format:" -ForegroundColor Yellow
    Write-Host "  e.g.: 1958d935-8ace-4a96-b7f1-4886ef9a3f54" -ForegroundColor Yellow

    # Press any key to continue...
    Write-Host 'Press any key to continue...'
    $null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')

    exit 1
}

# 2. Module Import and Connection to Graph API
try{
    Import-Module Microsoft.Graph.Identity.DirectoryManagement -ErrorAction Stop
}
catch{
    "Error was $_"
    $line = $_.InvocationInfo.ScriptLineNumber
    "Error was in Line $line"
}

try{
    Connect-mgGraph -Scopes Device.Read.All, Directory.ReadWrite.All, Directory.AccessAsUser.All -ErrorAction Stop
}
catch{
    "Error was $_"
    $line = $_.InvocationInfo.ScriptLineNumber
    "Error was in Line $line"
}

# 3. Retrieve Azure AD Device Object:
try{
    $AzureAdDevice = Get-MgDevice -DeviceId $DeviceId
}
catch{
    "Error was $_"
    $line = $_.InvocationInfo.ScriptLineNumber
    "Error was in Line $line"
    exit 1
}

$uri = $null
$uri = "https://graph.microsoft.com/beta/devices/" + $AzureAdDevice.id

try{
    $DeviceObj = $null
    $DeviceObj = Invoke-MgGraphRequest -Uri $uri -Method GET
}
catch{
    Write-Error "Error was $_"
    $line = $_.InvocationInfo.ScriptLineNumber
    Write-Error "Error was in Line $line"
}

if($DeviceObj -eq $null){
    Write-Error "no device object found with id: $($AzureAdDevice.id)"
    exit 2
}

# 4. Clear ExtensionAttribute on Azure AD Device Object:

try{
    Set-AadDeviceExtensionAttribute -AzureAdDevice $DeviceObj `
                                    -ExtensionAttributeName $ExtensionAttributeName `
                                    -ErrorAction Stop
    # 5. Script Completion
    Write-Host "Successfully cleared the value of the ExtensionAttribute $($ExtensionAttributeName) on the Device oject in Azure AD" -ForegroundColor Green
}
catch{
    Write-Error "Error was $_"
    $line = $_.InvocationInfo.ScriptLineNumber
    Write-Error "Error was in Line $line"
}
LosFlaIT/Clear-ExtensionAttributeOnAadDevice.ps1 at c07423f0d72b6cc1365ffd0b75c9eed0cb6e84fa · LosFla/LosFlaIT · GitHub: Clearing Azure AD Device Attribute Using PowerShell Script: A Step-by-Step Guide

Understanding the Script

  1. User Input Validation:
    • The script uses a regular expression pattern ($RegexObjectId) to validate the user’s input for the DeviceId.
    • The user is prompted to enter the objectId of the device they want to clear, and the input is validated against the expected format.
    • If the input does not match the expected format, an error message is displayed, and the script exits.
  2. Module Import and Connection to Graph API:
    • The script attempts to import the Microsoft.Graph.Identity.DirectoryManagement module, which is necessary for working with Azure AD devices.
    • If the module import fails, an error message is displayed.
    • The script then connects to the Graph API using the Connect-mgGraph cmdlet, specifying the required scopes.
    • If the connection fails, an error message is displayed.
  3. Retrieve Azure AD Device Object:
    • The script uses the Get-MgDevice cmdlet to retrieve the Azure AD device object based on the provided DeviceId.
    • If the retrieval fails, an error message is displayed, and the script exits.
  4. Clear ExtensionAttribute on Azure AD Device Object:
    • The script calls the Set-AadDeviceExtensionAttribute function, passing the necessary parameters.
    • If the clearing process fails, an error message is displayed.
  5. Script Completion:
    • If the clearing process is successful, a success message is displayed, indicating that the ExtensionAttribute’s value has been cleared on the Azure AD device object.
    • If any errors occur during the script execution, error messages are displayed, indicating the line number where the error occurred.

Conclusion

Managing device attributes in Azure AD is crucial for efficient device management and security. With the provided PowerShell script, you can easily clear specific attributes on Azure AD device objects. By running the script in the console and incorporating user prompts, you can provide a seamless and interactive experience for managing Azure AD devices. Remember to adapt the script to your specific needs and explore other possibilities offered by Azure AD and PowerShell to further enhance your device management capabilities.

Similar Posts

Leave a Reply

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