All scripts
Automation 930

Get-InactiveEntraDevices

Finds Entra ID devices with no sign-in activity in a given window, so you can clean up stale device records before an audit instead of during one.

Get-InactiveEntraDevices.ps1
<#
.SYNOPSIS
    Get-InactiveEntraDevices.ps1 - Finds Entra ID devices that haven't checked in recently.

.DESCRIPTION
    Queries Microsoft Graph for all registered devices and flags any that haven't
    signed in within a given number of days. Useful before a device compliance
    audit or a stale-device cleanup pass. Requires Graph scope: Device.Read.All

.AUTHOR
    Shehryar Hassan

.EXAMPLE
    .\Get-InactiveEntraDevices.ps1 -InactiveDays 90 -OutputPath ".\StaleDevices.csv"
#>

param(
    [Parameter(Mandatory=$false)]
    [int]$InactiveDays = 90,

    [Parameter(Mandatory=$false)]
    [string]$OutputPath = ".\StaleDevices.csv"
)

Write-Host "=============================================" -ForegroundColor Cyan
Write-Host "  Entra ID Inactive Device Finder" -ForegroundColor Cyan
Write-Host "=============================================" -ForegroundColor Cyan

if (-not (Get-MgContext)) {
    Write-Host "[INFO] Connecting to Microsoft Graph..." -ForegroundColor Yellow
    Connect-MgGraph -Scopes "Device.Read.All"
}

$cutoff = (Get-Date).AddDays(-$InactiveDays)
Write-Host "[INFO] Flagging devices with no activity since $($cutoff.ToString('yyyy-MM-dd'))" -ForegroundColor Gray

$devices = Get-MgDevice -All -Property Id, DisplayName, OperatingSystem, ApproximateLastSignInDateTime, AccountEnabled

$stale = $devices | Where-Object {
    $_.ApproximateLastSignInDateTime -and $_.ApproximateLastSignInDateTime -lt $cutoff
} | Select-Object DisplayName, OperatingSystem, AccountEnabled,
    @{n = 'LastSignIn'; e = { $_.ApproximateLastSignInDateTime } },
    @{n = 'DaysInactive'; e = { [math]::Round(((Get-Date) - $_.ApproximateLastSignInDateTime).TotalDays) } } |
    Sort-Object DaysInactive -Descending

$stale | Export-Csv -Path $OutputPath -NoTypeInformation

Write-Host "[SUCCESS] $($stale.Count) inactive device(s) written to: $OutputPath" -ForegroundColor Green
Write-Host "[INFO] Review before disabling or removing, some are legitimately dormant (loaner laptops, seasonal staff)." -ForegroundColor Yellow

Read it before you run it, and test in a safe tenant first.