Subscribe
Powershell

Microsoft Graph PowerShell SDK v2 Automation: Batch Offboarding, PIM Elevation & Forensic Audit Logs

Microsoft Graph PowerShell SDK v2 Automation: Batch Offboarding, PIM Elevation & Forensic Audit Logs
POWERSHELL & GRAPH API • ENTERPRISE IDENTITY AUTOMATION

With the complete retirement of legacy AzureAD and MSOnline PowerShell modules, enterprise systems engineers must standardize identity automation entirely on the Microsoft Graph PowerShell SDK v2. Modern security operations require robust, non-interactive authentication via certificate-backed app registrations and high-throughput batching. This production guide delivers ready-to-run PowerShell 7 scripts for automating emergency employee offboarding, requesting Just-In-Time (JIT) Privileged Identity Management (PIM) role elevations, and harvesting forensic audit trails with exponential backoff handling.

1. The Transition to Microsoft Graph SDK v2: Core Architectural Changes

Microsoft Graph SDK v2 introduces significant enhancements over v1 and legacy modules:

  • Split Modular Architecture: Instead of loading the massive monolithic SDK, administrators import lightweight sub-modules such as Microsoft.Graph.Authentication, Microsoft.Graph.Users, and Microsoft.Graph.Identity.Governance.
  • Native App-Only Certificate Auth: Direct support for X.509 certificate authentication via Azure Key Vault or local certificate store, eliminating secrets stored in plaintext scripts.
  • Automatic HTTP 429 Throttle Handling: Built-in retry handlers that respect Retry-After response headers from the Microsoft Graph gateway.

2. Non-Interactive Certificate Authentication

# Authenticate unattended daemon script using Certificate Thumbprint
$TenantId = "contoso.onmicrosoft.com"
$ClientId = "00000000-0000-0000-0000-000000000000"
$Thumbprint = "A1B2C3D4E5F678901234567890ABCDEF12345678"

Connect-MgGraph -ClientId $ClientId -TenantId $TenantId -CertificateThumbprint $Thumbprint -NoWelcome

3. Production Script: Automated Emergency Employee Offboarding

When an employee departs or security incidents occur, identity revocation must happen across all cloud surfaces simultaneously. This production script revokes refresh tokens, disables the user account, removes cloud license assignments, and initiates remote mobile device wipe:

param(
    [Parameter(Mandatory=$true)]
    [string]$TargetUserUPN,
    
    [Parameter(Mandatory=$true)]
    [string]$IncidentTicketId
)

Import-Module Microsoft.Graph.Users -ErrorAction Stop
Import-Module Microsoft.Graph.DeviceManagement -ErrorAction Stop

$user = Get-MgUser -UserId $TargetUserUPN -Property Id, UserPrincipalName, AccountEnabled, AssignedLicenses
if (-not $user) {
    throw "Target user $TargetUserUPN not found in Microsoft Entra ID."
}

Write-Host "[1/4] Revoking all active sign-in sessions and refresh tokens..." -ForegroundColor Yellow
Revoke-MgUserSignInSession -UserId $user.Id | Out-Null

Write-Host "[2/4] Disabling Entra ID account..." -ForegroundColor Yellow
Update-MgUser -UserId $user.Id -AccountEnabled:$false

Write-Host "[3/4] Removing all assigned M365 licenses..." -ForegroundColor Yellow
$licensesToRemove = $user.AssignedLicenses | ForEach-Object { $_.SkuId }
if ($licensesToRemove) {
    Set-MgUserLicense -UserId $user.Id -AddLicenses @() -RemoveLicenses $licensesToRemove | Out-Null
}

Write-Host "[4/4] Locating and wiping registered Intune mobile devices..." -ForegroundColor Yellow
$devices = Get-MgUserManagedDevice -UserId $user.Id
foreach ($device in $devices) {
    Write-Host "Triggering enterprise wipe on $($device.DeviceName) ($($device.OperatingSystem))..."
    Wipe-MgDeviceManagementManagedDevice -ManagedDeviceId $device.Id -KeepEnrollmentData:$false -KeepUserData:$false
}

Write-Host "Offboarding completed for $TargetUserUPN under incident $IncidentTicketId" -ForegroundColor Green

4. Automating Just-In-Time (JIT) PIM Role Elevation

Elevate into privileged administrative roles (e.g., Global Reader or Security Administrator) on-demand with automated justification and ticket referencing:

Import-Module Microsoft.Graph.Identity.Governance

$roleDefinitionId = "f28a1f50-f6e7-4571-818b-6a12f2af6b6c" # Security Administrator
$myUserId = (Get-MgContext).Account

$params = @{
    action = "selfActivate"
    principalId = $myUserId
    roleDefinitionId = $roleDefinitionId
    directoryScopeId = "/"
    justification = "Incident SEC-2026-9901 Investigation"
    scheduleInfo = @{
        startDateTime = (Get-Date).ToUniversalTime()
        expiration = @{
            type = "afterDuration"
            duration = "PT4H" # 4 Hours Elevation
        }
    }
}

New-MgRoleManagementDirectoryRoleAssignmentScheduleRequest -BodyParameter $params
Write-Host "PIM Role Elevation Requested for 4 Hours." -ForegroundColor Green
Author: Shivam Tiwari | Senior Enterprise Cloud & Security Architect
Published on CloudKnowledge.in — Battle-Tested Enterprise IT & Multi-Cloud Engineering.
Architect's Toolkit Recommendation Verified Production Tools • AdSense Compliant

Recommended Hardware & Reference Architecture Literature

Tested tools and authoritative documentation to implement the architectures covered in this lab:

★ 4.8 • HARDWARE SECURITY
YubiKey 5 NFC Security Key
FIDO2 / Passwordless Step-Up Auth
View on Amazon (₹5,499) ↗
★ 4.9 • DISTRIBUTED SYSTEMS
Designing Data-Intensive Apps
By Martin Kleppmann (O'Reilly)
View on Amazon (₹1,250) ↗
Explore high-IOPS lab SSDs, cloud cert guides, and developer mice. Browse Full Architecture Toolkit →
TAGS: #Cybersecurity #Entra ID #Microsoft Graph SDK v2 #PIM #powershell #Security Automation

Leave a Reply

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