Get Windows LAPS Audit
This script lists all device local credential records escrowed by Windows LAPS in Entra ID and cross-references them with Intune Windows devices. It reports which devices have no escrowed local administrator password at all, and which have passwords older than the rotation threshold - both signs that the LAPS policy is not applying. Only credential metadata (device name, backup time) is read; actual passwords are never retrieved by this script.
New to runbook deployment? Follow the step-by-step guide from the Deploy to Azure button to the first scheduled run, including granting Graph permissions to the managed identity.
// QUALITY CHECKS
Validation status
Quality checks
All checks pass- ParsePass
- LintPass
- MetadataPass
- Runbook-readyPass
- Module depsPass
Tests run automatically on every change. What does each check mean?
// REQUIRED PERMISSIONS
Microsoft Graph scopes
DeviceLocalCredential.ReadBasic.AllDeviceManagementManagedDevices.Read.AllAllows the app to read the properties of devices managed by Microsoft Intune, without a signed-in user.
Running this as an Azure Automation runbook? These scopes must be granted to the account's managed identity, which has no portal UI. The deployment walkthrough shows the exact Cloud Shell commands.
// CHANGELOG
Version history
Entry · 01
1.3 - Correctly treat an empty device-local-credentials response as an empty collection
Entry · 02
1.2 - Added Azure Automation contract validation, portal-safe boolean parameters, beta Graph endpoints, and terminating paging errors
Entry · 03
1.1 - Azure Automation now records script progress, outcomes, and summaries in job history
Entry · 04
1.0 - Initial release
// CODE
Source
<#
.TITLE
Get Windows LAPS Audit
.SYNOPSIS
Audits Windows LAPS password escrow: which devices have a backed-up local admin password and how old it is.
.DESCRIPTION
This script lists all device local credential records escrowed by Windows LAPS in
Entra ID and cross-references them with Intune Windows devices. It reports which
devices have no escrowed local administrator password at all, and which have
passwords older than the rotation threshold - both signs that the LAPS policy is
not applying. Only credential metadata (device name, backup time) is read; actual
passwords are never retrieved by this script.
.TAGS
Security,Compliance
.MINROLE
Intune Administrator
.PERMISSIONS
DeviceLocalCredential.ReadBasic.All,DeviceManagementManagedDevices.Read.All
.AUTHOR
Ugur Koc
.VERSION
1.3
.CHANGELOG
1.3 - Correctly treat an empty device-local-credentials response as an empty collection
1.2 - Added Azure Automation contract validation, portal-safe boolean parameters, beta Graph endpoints, and terminating paging errors
1.1 - Azure Automation now records script progress, outcomes, and summaries in job history
1.0 - Initial release
.LASTUPDATE
2026-07-30
.EXAMPLE
.\get-windows-laps-audit.ps1
Audits LAPS escrow state for all Windows devices with a 60-day age threshold
.EXAMPLE
.\get-windows-laps-audit.ps1 -MaxPasswordAgeDays 30 -ExportToCsv "true"
Flags passwords older than 30 days and exports the audit to CSV
.NOTES
- Requires Microsoft.Graph.Authentication module
- Reading LAPS credential metadata is limited to specific roles; Intune Administrator is one of the allowed roles
- This script uses DeviceLocalCredential.ReadBasic.All and never retrieves password values
- Devices are matched between the LAPS store and Intune via the Entra device ID
- Uses beta Graph endpoints for the device local credentials surface
- Local interactive sign-in uses the MgGraphCommunity module to avoid the Graph SDK's mandatory WAM broker on Windows
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $false, HelpMessage = "Password age in days above which escrow is flagged as stale")]
[ValidateRange(1, 365)]
[int]$MaxPasswordAgeDays = 60,
[Parameter(Mandatory = $false, HelpMessage = "Export results to CSV")]
[ValidateSet("true", "false", "1", "0", '$true', '$false')]
[string]$ExportToCsv,
[Parameter(Mandatory = $false, HelpMessage = "Output path for exports")]
[string]$OutputPath = ".",
[Parameter(Mandatory = $false, HelpMessage = "Force module installation without prompting")]
[ValidateSet("true", "false", "1", "0", '$true', '$false')]
[string]$ForceModuleInstall
)
# Normalize the local module-install override for Azure Automation parameter binding.
$forceModuleInstallRaw = [string]$ForceModuleInstall
Remove-Variable -Name ForceModuleInstall
if ([string]::IsNullOrWhiteSpace($forceModuleInstallRaw)) {
$ForceModuleInstall = $false
}
elseif ($forceModuleInstallRaw.Trim().ToLowerInvariant() -in @("true", "1", '$true')) {
$ForceModuleInstall = $true
}
elseif ($forceModuleInstallRaw.Trim().ToLowerInvariant() -in @("false", "0", '$false')) {
$ForceModuleInstall = $false
}
else {
throw "Parameter 'ForceModuleInstall' accepts only true, false, 1, 0, $true, or $false."
}
# Azure Automation supplies portal parameter values as strings. Normalize the
# public boolean parameters once so local and runbook execution use real booleans.
foreach ($runbookBooleanParameter in @('ExportToCsv')) {
$runbookBooleanRaw = [string](Get-Variable -Name $runbookBooleanParameter -ValueOnly)
Remove-Variable -Name $runbookBooleanParameter
if ([string]::IsNullOrWhiteSpace($runbookBooleanRaw)) {
Set-Variable -Name $runbookBooleanParameter -Value $false
continue
}
switch ($runbookBooleanRaw.Trim().ToLowerInvariant()) {
{ $_ -in @("true", "1", '$true') } {
Set-Variable -Name $runbookBooleanParameter -Value $true
}
{ $_ -in @("false", "0", '$false') } {
Set-Variable -Name $runbookBooleanParameter -Value $false
}
default {
throw "Parameter '$runbookBooleanParameter' accepts only true, false, 1, 0, $true, or $false."
}
}
}
# ============================================================================
# ENVIRONMENT DETECTION AND SETUP
# ============================================================================
function Initialize-RequiredModule {
param(
[string[]]$ModuleNames,
[bool]$IsAutomationEnvironment,
[bool]$ForceInstall = $false
)
foreach ($ModuleName in $ModuleNames) {
Write-Verbose "Checking module: $ModuleName"
$module = Get-Module -ListAvailable -Name $ModuleName | Select-Object -First 1
if (-not $module) {
if ($IsAutomationEnvironment) {
throw "Module '$ModuleName' is not available in Azure Automation"
}
else {
Write-Information "Module '$ModuleName' not found. Installing..." -InformationAction Continue
if (-not $ForceInstall) {
$response = Read-Host "Install module '$ModuleName'? (Y/N)"
if ($response -notmatch '^[Yy]') {
throw "Module '$ModuleName' is required but installation was declined."
}
}
try {
$isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")
$scope = if ($isAdmin) { "AllUsers" } else { "CurrentUser" }
Install-Module -Name $ModuleName -Scope $scope -Force -AllowClobber -Repository PSGallery
Write-Information "✓ Successfully installed '$ModuleName'" -InformationAction Continue
}
catch {
throw "Failed to install module '$ModuleName': $($_.Exception.Message)"
}
}
}
Import-Module -Name $ModuleName -Force -ErrorAction Stop
}
}
# Detect execution environment
$IsAzureAutomation = $null -ne $PSPrivateMetadata.JobId.Guid
# Initialize required modules
$RequiredModules = @("Microsoft.Graph.Authentication")
# MgGraphCommunity gives WAM-free interactive sign-in for local runs
if (-not $IsAzureAutomation) {
$RequiredModules += "MgGraphCommunity"
}
try {
Initialize-RequiredModule -ModuleNames $RequiredModules -IsAutomationEnvironment $IsAzureAutomation -ForceInstall $ForceModuleInstall
Write-Verbose "✓ All required modules are available"
}
catch {
Write-Error "Module initialization failed: $_"
exit 1
}
# ============================================================================
# AUTHENTICATION
# ============================================================================
try {
if ($IsAzureAutomation) {
Write-Output "Connecting to Microsoft Graph using Managed Identity..."
Connect-MgGraph -Identity -NoWelcome -ErrorAction Stop
}
else {
Write-Output "Connecting to Microsoft Graph..."
$Scopes = @(
"DeviceLocalCredential.ReadBasic.All",
"DeviceManagementManagedDevices.Read.All"
)
Connect-MgGraphCommunity -Scopes $Scopes -NoWelcome -ErrorAction Stop
}
Write-Output "✓ Successfully connected to Microsoft Graph"
}
catch {
Write-Error "Failed to connect to Microsoft Graph: $($_.Exception.Message)"
exit 1
}
# ============================================================================
# HELPER FUNCTIONS
# ============================================================================
function Get-MgGraphAllPage {
param(
[string]$Uri,
[int]$DelayMs = 100
)
$allResults = @()
$nextLink = $Uri
do {
try {
if ($allResults.Count -gt 0) {
Start-Sleep -Milliseconds $DelayMs
}
$response = Invoke-MgGraphRequest -Uri $nextLink -Method GET
if ($null -ne $response.value) {
$allResults += $response.value
}
else {
$allResults += $response
}
$nextLink = $response.'@odata.nextLink'
}
catch {
if ($_.Exception.Message -like "*429*") {
Write-Information "Rate limit hit, waiting 60 seconds..." -InformationAction Continue
Start-Sleep -Seconds 60
continue
}
throw "Error fetching data: $($_.Exception.Message)"
}
} while ($nextLink)
return $allResults
}
# ============================================================================
# MAIN SCRIPT LOGIC
# ============================================================================
try {
Write-Output "Retrieving Windows LAPS credential records..."
$lapsRecords = Get-MgGraphAllPage -Uri "https://graph.microsoft.com/beta/directory/deviceLocalCredentials?`$select=id,deviceName,lastBackupDateTime"
Write-Output "✓ Found $(@($lapsRecords).Count) escrowed LAPS records"
Write-Output "Retrieving Intune Windows devices..."
$windowsDevices = Get-MgGraphAllPage -Uri "https://graph.microsoft.com/beta/deviceManagement/managedDevices?`$filter=operatingSystem eq 'Windows'&`$select=id,deviceName,azureADDeviceId,lastSyncDateTime,userPrincipalName"
Write-Output "✓ Found $(@($windowsDevices).Count) Windows devices"
# LAPS record id is the Entra device ID; index for the cross-reference
$lapsByDeviceId = @{}
foreach ($record in $lapsRecords) {
$lapsByDeviceId[$record.id] = $record
}
$now = Get-Date
[System.Collections.Generic.List[Object]]$report = @()
foreach ($device in $windowsDevices) {
$lapsRecord = if ($device.azureADDeviceId -and $lapsByDeviceId.ContainsKey($device.azureADDeviceId)) {
$lapsByDeviceId[$device.azureADDeviceId]
}
else {
$null
}
$lastBackup = if ($lapsRecord -and $lapsRecord.lastBackupDateTime) {
[DateTime]::Parse($lapsRecord.lastBackupDateTime.ToString())
}
else {
$null
}
$ageDays = if ($lastBackup) { [math]::Round(($now - $lastBackup).TotalDays, 1) } else { $null }
$status = if (-not $lapsRecord) { "NotEscrowed" }
elseif ($null -eq $ageDays) { "EscrowedNoTimestamp" }
elseif ($ageDays -gt $MaxPasswordAgeDays) { "Stale" }
else { "Healthy" }
$report.Add([PSCustomObject]@{
DeviceName = $device.deviceName
User = $device.userPrincipalName
EntraDeviceId = $device.azureADDeviceId
LastBackup = if ($lastBackup) { $lastBackup.ToString("yyyy-MM-dd HH:mm") } else { "" }
PasswordAgeDays = $ageDays
Status = $status
})
}
# ----- Display results -----
Write-Output "`nWINDOWS LAPS AUDIT"
Write-Output ("=" * 50)
Write-Output "Stale threshold: $MaxPasswordAgeDays days | Generated: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')"
Write-Output ("=" * 50)
$statusOrder = @("NotEscrowed", "Stale", "EscrowedNoTimestamp", "Healthy")
foreach ($statusName in $statusOrder) {
$statusDevices = @($report | Where-Object { $_.Status -eq $statusName })
if ($statusDevices.Count -eq 0) { continue }
Write-Output "`n[$statusName] $($statusDevices.Count) device(s)"
if ($statusName -ne "Healthy") {
foreach ($row in ($statusDevices | Sort-Object DeviceName)) {
$line = " $($row.DeviceName) | $($row.User)"
if ($row.LastBackup) { $line += " | last backup: $($row.LastBackup) ($($row.PasswordAgeDays) days)" }
Write-Output $line
}
}
}
if (@($report | Where-Object { $_.Status -eq "NotEscrowed" }).Count -gt 0) {
Write-Output "`nDevices without escrow either have no Windows LAPS policy assigned or have not rotated since policy assignment."
}
# Summary
$escrowedCount = @($report | Where-Object { $_.Status -ne "NotEscrowed" }).Count
$staleCount = @($report | Where-Object { $_.Status -eq "Stale" }).Count
Write-Output "`n"
Write-Output ("=" * 50)
Write-Output "Summary: $(@($windowsDevices).Count) Windows devices | $escrowedCount escrowed | $staleCount stale | $(@($windowsDevices).Count - $escrowedCount) not escrowed"
Write-Output ("=" * 50)
# Export to CSV if requested
if ($ExportToCsv) {
$timestamp = Get-Date -Format "yyyy-MM-dd_HH-mm-ss"
$csvPath = Join-Path $OutputPath "Windows_LAPS_Audit_$timestamp.csv"
$report | Export-Csv -Path $csvPath -NoTypeInformation -Encoding UTF8
Write-Output "✓ CSV report saved: $csvPath"
}
}
catch {
Write-Error "Script execution failed: $($_.Exception.Message)"
exit 1
}
finally {
try {
$null = Disconnect-MgGraph
Write-Output "✓ Disconnected from Microsoft Graph"
}
catch {
Write-Verbose "Graph disconnection completed"
}
}
// NOTES
Author notes
- Requires Microsoft.Graph.Authentication module - Reading LAPS credential metadata is limited to specific roles; Intune Administrator is one of the allowed roles - This script uses DeviceLocalCredential.ReadBasic.All and never retrieves password values - Devices are matched between the LAPS store and Intune via the Entra device ID - Uses beta Graph endpoints for the device local credentials surface - Local interactive sign-in uses the MgGraphCommunity module to avoid the Graph SDK's mandatory WAM broker on Windows
// RELATED
Scripts that travel together.
Picked by shared tags, category, and script type — nothing magic, just metadata overlap.
Multi-Admin Approval Compliance Dashboard Report
This script connects to Microsoft Graph and analyzes Multi-Admin Approval configurations, usage patterns, and compliance metrics across your Intune environment. It generates detailed reports showing MAA coverage gaps, approval statistics, admin permissions, and trends. The script helps organizations ensure proper implementation of MAA controls and identify areas for security improvement. Reports are generated in both HTML and CSV formats for different audiences.
ComplianceSecurityMulti-Admin Approval Pending Requests Monitor
This script is designed to run as a scheduled Azure Automation runbook that monitors Multi-Admin Approval requests in Microsoft Intune and identifies pending approval requests. It tracks new requests, monitors request age, identifies approvers, and sends email notifications to administrators with detailed request information and direct links to the Intune portal. The script helps maintain security compliance by ensuring timely review of administrative changes and provides visibility into the MAA approval workflow. Key Features: - Monitors all MAA pending requests across protected resources - Tracks request age and highlights urgent requests - Identifies and notifies appropriate approvers - Provides direct links to Intune portal for quick action - Tracks previously notified requests to avoid spam - Sends escalation alerts for aging requests - Supports both Azure Automation runbook and local execution - HTML formatted email reports with actionable insights - Uses Microsoft Graph Mail API exclusively
SecurityComplianceBitLocker Keys Backup to Azure Key Vault
This script connects to Microsoft Graph API to retrieve BitLocker recovery keys for Windows devices, then stores them securely in Azure Key Vault using REST API. Each key is stored as a secret with device information (name and serial number) included in tags. Authentication uses the MgGraphCommunity module (WAM-free) and acquires two separate tokens with the correct audiences: a device code sign-in for Azure Key Vault (https://vault.azure.net) and an interactive browser sign-in for Microsoft Graph. No Az modules are needed. On first run, you will be prompted to consent to the required permissions including Key Vault access.
SecurityCompliance