← SCRIPT LIBRARY

Active Directory · READ-ONLY / LOCAL CSV · v1.0.0

AD password age review

Count visible users in one approved OU by recorded password-set age, including zero and unknown values.

Lab validation pending

Offline tests do not establish live directory behavior. Review the source and run first in a small authorized lab. Nothing runs in this browser.

What you’ll need

  • Windows PowerShell 5.1 and RSAT ActiveDirectory module
  • Existing protected local output folder
  • Delegated read access to selected OU and pwdLastSet; no writes.

Run locally

Replace fictional inputs with values approved for your environment. Use an access-controlled local folder for output.

.\Export-SwpADPasswordAgeReview.ps1 -SearchBase 'OU=Lab,DC=mylab,DC=dev' -Server 'dc01.mylab.dev' -AgeDays 90 -OutputDirectory '.\Reports'

Read the results

FieldMeaning
BucketZero, AtOrAboveThreshold, BelowThreshold, or Unknown.
CountNumber of visible user objects in this bucket.
AgeDaysInclusive elapsed-day threshold (default 90).
ReportAsOfUtcFrozen UTC run timestamp.
  • Zero does not prove that a password was never assigned. Missing, invalid and future values are Unknown.
  • Password age does not establish inactivity or actual expiry. Both enabled and disabled users are included.
  • OneLevel is the default; use -SearchScope Subtree explicitly for nested OUs. Existing files are not overwritten.

Keep the output local and protected. A successful report does not prove complete directory visibility; do not use it by itself to change or remove accounts or groups.

Complete source

The display, clipboard copy, download and GitHub link refer to the same pinned source.

Export-SwpADPasswordAgeReview.ps1POWERSHELL / READ ONLY
#requires -Version 5.1
<#
.SYNOPSIS
    AD password age review.
.DESCRIPTION
    Count visible user objects by elapsed time since recorded password set, without exporting identities.
    Makes a paged, read-only query against one explicit organizational unit.
    Writes aggregate counts only; review and protect the CSV before sharing.
    Uses one frozen UTC instant and an inclusive age threshold.
    Zero pwdLastSet may mean a password change required at next sign-in or no assigned password; it proves neither. Password age is not inactivity or actual password expiry.
.PARAMETER SearchBase
    Distinguished name of the authorized OU to query. No default domain scope.
.PARAMETER SearchScope
    OneLevel (default) or Subtree (includes nested OUs).
.PARAMETER Server
    Optional approved AD DS domain controller. Otherwise use normal module selection.
.PARAMETER OutputDirectory
    Existing local filesystem folder. Defaults to the current directory.
.PARAMETER AgeDays
    Elapsed-day review threshold (1 to 3650), default 90.
.EXAMPLE
    .\Export-SwpADPasswordAgeReview.ps1 -SearchBase "OU=Lab,DC=mylab,DC=dev" -AgeDays 90
.NOTES
    ShellWePlay version 1.0.0 (2026-11-29), initial release. Lab validation pending.
    Windows PowerShell 5.1, RSAT ActiveDirectory and read access to the OU and pwdLastSet.
    CSV: Bucket (Zero, AtOrAboveThreshold, BelowThreshold, Unknown), Count, AgeDays, ReportAsOfUtc.
    Missing, malformed and future values are Unknown; counts include enabled and disabled users.
.LINK
    https://learn.microsoft.com/powershell/module/activedirectory/get-aduser
    https://learn.microsoft.com/en-us/windows/win32/adschema/a-pwdlastset
#>
[CmdletBinding()]
param(
    [Parameter(Mandatory)]
    [ValidatePattern('(?i)^(OU=).+')]
    [string]$SearchBase,

    [ValidateSet('OneLevel', 'Subtree')]
    [string]$SearchScope = 'OneLevel',

    [ValidateNotNullOrEmpty()]
    [string]$Server,

    [ValidateNotNullOrEmpty()]
    [string]$OutputDirectory = '.'
,

    [ValidateRange(1, 3650)]
    [int]$AgeDays = 90
)

Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'

# Resolve a literal directory before querying; no folders are created automatically.
$destination = Get-Item -LiteralPath $OutputDirectory
if ($destination -isnot [System.IO.DirectoryInfo]) {
    throw 'OutputDirectory must be an existing filesystem directory.'
}

Import-Module ActiveDirectory -ErrorAction Stop
$query = @{
    Filter = '*'
    SearchBase = $SearchBase
    SearchScope = $SearchScope
    ResultPageSize = 500
    ErrorAction = 'Stop'
    Properties = @('pwdLastSet')
}
if ($PSBoundParameters.ContainsKey('Server')) {
    $query.Server = $Server
}

# Do not emit a partial CSV if the directory query fails partway through.
$now = [DateTime]::UtcNow
$cutoff = $now.AddDays(-$AgeDays)
$counts = [ordered]@{ Zero = 0L; AtOrAboveThreshold = 0L; BelowThreshold = 0L; Unknown = 0L }
Get-ADUser @query | ForEach-Object {
    $property = $_.PSObject.Properties['pwdLastSet']
    $raw = if ($null -ne $property) { $property.Value }
    # LDAP pwdLastSet is a signed 64-bit Windows FILETIME; zero is special.
    $value = 0L
    if ($null -eq $raw -or -not [long]::TryParse([string]$raw, [ref]$value) -or $value -lt 0) {
        $counts.Unknown++
    }
    elseif ($value -eq 0) { $counts.Zero++ }
    else {
        try { $date = [datetime]::FromFileTimeUtc($value) }
        catch { $date = $null }
        if ($null -eq $date -or $date -gt $now) { $counts.Unknown++ }
        elseif ($date -le $cutoff) { $counts.AtOrAboveThreshold++ }
        else { $counts.BelowThreshold++ }
    }
}
$rows = foreach ($key in $counts.Keys) {
    [pscustomobject]@{ Bucket = $key; Count = $counts[$key]; AgeDays = $AgeDays; ReportAsOfUtc = $now.ToString('o') }
}

# Text from the directory is never written to these reports. The first row is a
# fixed header even if this OU contains no visible objects. CreateNew is atomic
# and never overwrites an existing report. Acquire it before managing cleanup.
$columns = @('Bucket', 'Count', 'AgeDays', 'ReportAsOfUtc')
$header = ($columns | ForEach-Object { '"{0}"' -f $_ }) -join ','
$stamp = $now.ToString('yyyyMMddTHHmmssfffZ', [System.Globalization.CultureInfo]::InvariantCulture)
$path = Join-Path -Path $destination.FullName -ChildPath ('Export-SwpADPasswordAgeReview-{0}.csv' -f $stamp)
$file = [System.IO.File]::Open($path, [System.IO.FileMode]::CreateNew, [System.IO.FileAccess]::Write, [System.IO.FileShare]::None)
try {
    try {
        $writer = [System.IO.StreamWriter]::new($file, [System.Text.UTF8Encoding]::new($true))
        try {
            $writer.WriteLine($header)
            $rows | Select-Object -Property $columns | ConvertTo-Csv -NoTypeInformation |
                Select-Object -Skip 1 | ForEach-Object { $writer.WriteLine($_) }
        }
        finally {
            $writer.Dispose()
        }
    }
    finally {
        $file.Dispose()
    }
}
catch {
    try {
        [System.IO.File]::Delete($path)
    }
    catch {
        Write-Warning 'Could not remove the incomplete local report.'
    }
    throw
}
Write-Host "Visible users: $(($counts.Values | Measure-Object -Sum).Sum); report: $path"
Get-Item -LiteralPath $path

Microsoft references