#requires -Version 5.1 <# .SYNOPSIS Read-only AD DS inventory using Microsoft RSAT and Windows PowerShell 5.1. .DESCRIPTION Uses the current Windows identity. All directory operations are explicit Get-* calls to the Microsoft ActiveDirectory module. Optional GPO settings reports use the Microsoft GroupPolicy module. No directory writes, remote execution, software installation, credential prompts, or execution-policy changes occur. Only local report files/directories are written. Run as a standard domain user. Default scope: current user's domain, with forest-wide configuration inventory. CSV files go directly into C:\Temp\Output. Each run has a unique filename prefix. Missing permissions/connectivity are recorded, and independent queries continue. No attempt is made to grant access or elevate privileges. .PARAMETER Server Optional domain controller DNS hostname for the initial/current domain. .PARAMETER AllForestDomains Also query each domain in the discovered forest. A DC is selected per domain. Does not follow external trusts into other forests. .PARAMETER IncludeGpoReports Also generate full HTML/XML GPO reports if GroupPolicy RSAT is installed. .PARAMETER SkipGroupMembership Skip explicit membership edges to reduce query load and output volume. .EXAMPLE .\Get-ADReadOnlyInventory.ps1 .EXAMPLE .\Get-ADReadOnlyInventory.ps1 -Server dc01.example.local -AllForestDomains -IncludeGpoReports .NOTES Use 64-bit Windows PowerShell 5.1 on Windows Server 2022 with RSAT already installed. You need local write access to C:\Temp\Output (or -OutputPath). If denied, ask an administrator to create that folder and grant the account Modify permission on that folder only. Domain Admin/local elevation is not required by this script. Existing execution policy must permit this script. CSV: UTF-8, comma-delimited, invariant values, dates in UTC ISO 8601. Multi-value attributes are JSON arrays inside CSV cells. Empty results retain column headers. Manifest.csv distinguishes completed, empty, failed/partial, and skipped queries. Reports from failed queries, when present, end in .partial.csv and are incomplete. An empty value may mean unset OR not visible to the account; it is not proof of absence. AD can silently omit unreadable objects/attributes despite query success. Memberships.csv contains direct, explicit group member links, including nested group DNs. It does not expand nested membership, resolve foreign principals, or include primary group membership. PrimaryGroupID is exported for users and computers; join to a group SID's final RID to identify implicit primary groups. Group member lists are retrieved by RSAT (including its normal range handling). Very large groups may be slow or encounter ADWS/server limits; check the manifest. LastLogonDate uses replicated lastLogonTimestamp and can lag; this script does not calculate exact last logon across DCs. Account flags are reported, not risk scores. The inventory is not an atomic snapshot or a full AD/security audit. It does not query passwords, LAPS secrets, gMSA managed passwords, deleted objects, directory ACLs, event logs, DNS/DHCP zones, SYSVOL scripts, or replication health. GPO metadata includes domain/OU links as raw gPLink/gPOptions; optional GPO reports include settings accessible through AD/SYSVOL. Linked site GPOs are in Sites.csv. Treat outputs as sensitive directory information and store with appropriate ACLs. #> [CmdletBinding()] param( [ValidateNotNullOrEmpty()][string]$OutputPath = 'C:\Temp\Output', [string]$Server, [switch]$AllForestDomains, [switch]$IncludeGpoReports, [switch]$SkipGroupMembership ) Set-StrictMode -Version 2.0 $ErrorActionPreference = 'Stop' $started = [DateTime]::UtcNow $runId = 'ADInventory_{0}_{1}' -f $started.ToString('yyyyMMddTHHmmssZ'), ([guid]::NewGuid().ToString('N').Substring(0,8)) $manifest = New-Object 'System.Collections.Generic.List[object]' $failures = New-Object 'System.Collections.Generic.List[object]' # Local filesystem only: refuse UNC/network destinations and non-filesystem drives. if ($OutputPath -notmatch '^[A-Za-z]:\\' -or $OutputPath.Contains('::')) { throw 'OutputPath must be an absolute local drive path, such as C:\Temp\Output.' } $drive = Get-PSDrive -Name $OutputPath.Substring(0,1) -PSProvider FileSystem if ($drive.DisplayRoot -like '\\*') { throw 'Mapped network output drives are not supported.' } try { $null = New-Item -ItemType Directory -Path $OutputPath -Force $probe = Join-Path $OutputPath ($runId + '_write-test.tmp') 'Local output write test' | Set-Content -LiteralPath $probe -Encoding UTF8 Remove-Item -LiteralPath $probe } catch { throw "Cannot write reports to '$OutputPath'. Have an administrator grant this user local folder access. $($_.Exception.Message)" } function Get-ReportPath { param([string]$Name) Join-Path $OutputPath ($runId + '_' + $Name) } function Add-Failure { param([string]$Task, [System.Management.Automation.ErrorRecord]$Record) $failures.Add([pscustomobject]@{ TimeUtc = [DateTime]::UtcNow.ToString('o'); Task = $Task Message = $Record.Exception.Message; ErrorId = $Record.FullyQualifiedErrorId Category = [string]$Record.CategoryInfo.Category }) Write-Warning ("{0}: {1}" -f $Task, $Record.Exception.Message) } function Convert-Cell { param($Value) if ($null -eq $Value) { return '' } if ($Value -is [DateTime]) { return $Value.ToUniversalTime().ToString('o') } if ($Value -is [TimeSpan]) { return $Value.ToString('c', [Globalization.CultureInfo]::InvariantCulture) } if ($Value -is [string]) { return $Value } if ($Value -is [System.Collections.IEnumerable]) { $items = @($Value | ForEach-Object { Convert-Cell $_ }) return ConvertTo-Json -InputObject $items -Compress -Depth 4 } if ($Value -is [System.IFormattable]) { return $Value.ToString($null, [Globalization.CultureInfo]::InvariantCulture) } return [string]$Value } function Export-Query { param([string]$Name, [string[]]$Columns, [scriptblock]$Query) $path = Get-ReportPath ($Name + '.csv') $counter = @{ Count = 0 } $state = 'Completed' $message = '' Write-Host "Querying $Name ..." # Start with a header even if the query is empty or fails before returning data. $empty = [ordered]@{} foreach ($column in $Columns) { $empty[$column] = '' } ([pscustomobject]$empty | ConvertTo-Csv -NoTypeInformation | Select-Object -First 1) | Set-Content -LiteralPath $path -Encoding UTF8 try { & $Query | ForEach-Object { $source = $_ $row = [ordered]@{} foreach ($column in $Columns) { # Missing/unreadable properties are blank rather than throwing. $property = $source.PSObject.Properties[$column] if ($null -eq $property) { $row[$column] = '' } else { $row[$column] = Convert-Cell $property.Value } } $counter.Count++ [pscustomobject]$row } | Export-Csv -LiteralPath $path -NoTypeInformation -Encoding UTF8 -Append if ($counter.Count -eq 0) { $state = 'Empty' } } catch { $state = 'FailedOrPartial' $message = $_.Exception.Message Add-Failure $Name $_ $partial = Get-ReportPath ($Name + '.partial.csv') Move-Item -LiteralPath $path -Destination $partial $path = $partial } $manifest.Add([pscustomobject]@{ Query = $Name; Status = $state; RowsProcessed = $counter.Count File = [IO.Path]::GetFileName($path); Message = $message }) } function Add-Skipped { param([string]$Name, [string]$Reason) $manifest.Add([pscustomobject]@{ Query = $Name; Status = 'Skipped'; RowsProcessed = 0; File = ''; Message = $Reason }) } $fatal = $false $initialServer = $Server $gpoAvailable = $false try { Import-Module ActiveDirectory -ErrorAction Stop if ($IncludeGpoReports) { try { Import-Module GroupPolicy -ErrorAction Stop; $gpoAvailable = $true } catch { Add-Failure 'Load optional GroupPolicy module' $_ } } $initialArgs = @{} if ($Server) { $initialArgs.Server = $Server } $initialDomain = ActiveDirectory\Get-ADDomain @initialArgs if (-not $initialServer) { $initialServer = (ActiveDirectory\Get-ADDomainController -Discover -DomainName $initialDomain.DNSRoot).HostName | Select-Object -First 1 } $forest = ActiveDirectory\Get-ADForest -Server $initialServer $root = ActiveDirectory\Get-ADRootDSE -Server $initialServer Export-Query 'Forest' @('Name','RootDomain','ForestMode','Domains','Sites','GlobalCatalogs','SchemaMaster','DomainNamingMaster','UPNSuffixes','SPNSuffixes') { $forest } Export-Query 'RootDSE' @('dnsHostName','defaultNamingContext','configurationNamingContext','schemaNamingContext','rootDomainNamingContext','domainControllerFunctionality','domainFunctionality','forestFunctionality') { $root } Export-Query 'SchemaVersion' @('DistinguishedName','objectVersion','whenChanged') { ActiveDirectory\Get-ADObject -Identity $root.SchemaNamingContext -Server $initialServer -Properties @('objectVersion','whenChanged') } Export-Query 'Sites' @('Name','DistinguishedName','Description','Location','gPLink','gPOptions') { ActiveDirectory\Get-ADReplicationSite -Filter * -Server $initialServer -Properties @('Description','Location','gPLink','gPOptions') } Export-Query 'Subnets' @('Name','DistinguishedName','Site','Location','Description') { ActiveDirectory\Get-ADReplicationSubnet -Filter * -Server $initialServer -Properties @('Location','Description') } Export-Query 'SiteLinks' @('Name','DistinguishedName','SitesIncluded','Cost','ReplicationFrequencyInMinutes','InterSiteTransportProtocol') { ActiveDirectory\Get-ADReplicationSiteLink -Filter * -Server $initialServer } $domains = @($initialDomain.DNSRoot) if ($AllForestDomains) { $domains = @($forest.Domains | Sort-Object) } foreach ($domainName in $domains) { $tag = $domainName -replace '[^A-Za-z0-9.-]', '_' try { if ($domainName -eq $initialDomain.DNSRoot) { $dc = $initialServer } else { $dc = (ActiveDirectory\Get-ADDomainController -Discover -DomainName $domainName).HostName | Select-Object -First 1 } $domain = ActiveDirectory\Get-ADDomain -Server $dc $base = $domain.DistinguishedName } catch { Add-Failure "$tag domain discovery" $_ $manifest.Add([pscustomobject]@{ Query = "$tag domain discovery"; Status = 'FailedOrPartial'; RowsProcessed = 0; File = ''; Message = $_.Exception.Message }) continue } Export-Query ($tag + '_Domain') @('DNSRoot','NetBIOSName','DistinguishedName','DomainSID','DomainMode','PDCEmulator','RIDMaster','InfrastructureMaster','ParentDomain','ChildDomains','ReplicaDirectoryServers','ReadOnlyReplicaDirectoryServers','ComputersContainer','UsersContainer') { $domain } Export-Query ($tag + '_DomainControllers') @('Name','HostName','IPv4Address','IPv6Address','Site','OperatingSystem','OperatingSystemVersion','IsGlobalCatalog','IsReadOnly','OperationMasterRoles','ComputerObjectDN','ServerObjectDN') { ActiveDirectory\Get-ADDomainController -Filter * -Server $dc } Export-Query ($tag + '_Trusts') @('Name','Source','Target','Direction','TrustType','ForestTransitive','IntraForest','SelectiveAuthentication','SIDFilteringForestAware','SIDFilteringQuarantined','DisallowTransivity') { ActiveDirectory\Get-ADTrust -Filter * -Server $dc } Export-Query ($tag + '_DefaultPasswordPolicy') @('DistinguishedName','ComplexityEnabled','MinPasswordLength','PasswordHistoryCount','MinPasswordAge','MaxPasswordAge','LockoutThreshold','LockoutDuration','LockoutObservationWindow','ReversibleEncryptionEnabled') { ActiveDirectory\Get-ADDefaultDomainPasswordPolicy -Server $dc } Export-Query ($tag + '_FineGrainedPasswordPolicies') @('Name','DistinguishedName','Precedence','AppliesTo','ComplexityEnabled','MinPasswordLength','PasswordHistoryCount','MinPasswordAge','MaxPasswordAge','LockoutThreshold','LockoutDuration','LockoutObservationWindow','ReversibleEncryptionEnabled') { ActiveDirectory\Get-ADFineGrainedPasswordPolicy -Filter * -Server $dc } Export-Query ($tag + '_OUs') @('Name','DistinguishedName','Description','ManagedBy','ProtectedFromAccidentalDeletion','gPLink','gPOptions','whenCreated','whenChanged') { ActiveDirectory\Get-ADOrganizationalUnit -Filter * -SearchBase $base -Server $dc -ResultPageSize 500 -Properties @('Description','ManagedBy','ProtectedFromAccidentalDeletion','gPLink','gPOptions','whenCreated','whenChanged') } Export-Query ($tag + '_DomainGpoLinks') @('DistinguishedName','gPLink','gPOptions') { ActiveDirectory\Get-ADObject -Identity $base -Server $dc -Properties @('gPLink','gPOptions') } Export-Query ($tag + '_Users') @('SamAccountName','UserPrincipalName','Name','DisplayName','GivenName','Surname','DistinguishedName','SID','Enabled','Description','Mail','Department','Title','Company','Manager','AccountExpirationDate','PasswordLastSet','PasswordNeverExpires','PasswordNotRequired','LastLogonDate','LockedOut','adminCount','PrimaryGroupID','ServicePrincipalName','TrustedForDelegation','TrustedToAuthForDelegation','AccountNotDelegated','msDS-AllowedToDelegateTo','MemberOf','whenCreated','whenChanged') { ActiveDirectory\Get-ADUser -Filter * -SearchBase $base -Server $dc -ResultPageSize 500 -Properties @('DisplayName','Description','Mail','Department','Title','Company','Manager','AccountExpirationDate','PasswordLastSet','PasswordNeverExpires','PasswordNotRequired','LastLogonDate','LockedOut','adminCount','PrimaryGroupID','ServicePrincipalName','TrustedForDelegation','TrustedToAuthForDelegation','AccountNotDelegated','msDS-AllowedToDelegateTo','MemberOf','whenCreated','whenChanged') } Export-Query ($tag + '_Computers') @('Name','SamAccountName','DNSHostName','DistinguishedName','SID','Enabled','OperatingSystem','OperatingSystemVersion','OperatingSystemServicePack','Description','ManagedBy','LastLogonDate','PasswordLastSet','PrimaryGroupID','ServicePrincipalName','TrustedForDelegation','TrustedToAuthForDelegation','msDS-AllowedToDelegateTo','msDS-SupportedEncryptionTypes','MemberOf','whenCreated','whenChanged') { ActiveDirectory\Get-ADComputer -Filter * -SearchBase $base -Server $dc -ResultPageSize 500 -Properties @('DNSHostName','OperatingSystem','OperatingSystemVersion','OperatingSystemServicePack','Description','ManagedBy','LastLogonDate','PasswordLastSet','PrimaryGroupID','ServicePrincipalName','TrustedForDelegation','TrustedToAuthForDelegation','msDS-AllowedToDelegateTo','msDS-SupportedEncryptionTypes','MemberOf','whenCreated','whenChanged') } Export-Query ($tag + '_Groups') @('Name','SamAccountName','DistinguishedName','SID','GroupCategory','GroupScope','Description','ManagedBy','Mail','adminCount','MemberOf','whenCreated','whenChanged') { ActiveDirectory\Get-ADGroup -Filter * -SearchBase $base -Server $dc -ResultPageSize 500 -Properties @('Description','ManagedBy','Mail','adminCount','MemberOf','whenCreated','whenChanged') } if ($SkipGroupMembership) { Add-Skipped ($tag + '_Memberships') 'SkipGroupMembership was specified.' } else { Export-Query ($tag + '_Memberships') @('GroupDN','GroupSID','GroupSamAccountName','MemberDN','MembershipType') { ActiveDirectory\Get-ADGroup -Filter * -SearchBase $base -Server $dc -ResultPageSize 500 -Properties @('member') | ForEach-Object { $group = $_ foreach ($memberDN in $group.member) { [pscustomobject]@{ GroupDN = $group.DistinguishedName; GroupSID = $group.SID GroupSamAccountName = $group.SamAccountName MemberDN = $memberDN; MembershipType = 'DirectExplicit' } } } } } Export-Query ($tag + '_ServiceAccounts') @('Name','SamAccountName','ObjectClass','DistinguishedName','SID','Enabled','DNSHostName','Description','ServicePrincipalName','PasswordLastSet','LastLogonDate','MemberOf','whenCreated','whenChanged') { ActiveDirectory\Get-ADServiceAccount -Filter * -SearchBase $base -Server $dc -ResultPageSize 500 -Properties @('Description','ServicePrincipalName','PasswordLastSet','LastLogonDate','MemberOf','whenCreated','whenChanged') } Export-Query ($tag + '_GpoMetadata') @('Name','DisplayName','DistinguishedName','gPCFileSysPath','gPCWQLFilter','flags','versionNumber','whenCreated','whenChanged') { ActiveDirectory\Get-ADObject -LDAPFilter '(objectClass=groupPolicyContainer)' -SearchBase ("CN=Policies,CN=System,$base") -Server $dc -ResultPageSize 500 -Properties @('DisplayName','gPCFileSysPath','gPCWQLFilter','flags','versionNumber','whenCreated','whenChanged') } if ($IncludeGpoReports -and $gpoAvailable) { foreach ($format in @('Html','Xml')) { $reportName = $tag + '_GpoSettings.' + $format.ToLowerInvariant() $reportPath = Get-ReportPath $reportName try { # Get-GPOReport reads AD/SYSVOL; -Path writes a local report only. GroupPolicy\Get-GPOReport -All -Domain $domainName -Server $dc -ReportType $format -Path $reportPath $manifest.Add([pscustomobject]@{ Query = $reportName; Status = 'Completed'; RowsProcessed = ''; File = [IO.Path]::GetFileName($reportPath); Message = '' }) } catch { Add-Failure $reportName $_ $partialName = '' if (Test-Path -LiteralPath $reportPath) { $partialName = [IO.Path]::GetFileName($reportPath) + '.partial' Move-Item -LiteralPath $reportPath -Destination (Join-Path $OutputPath $partialName) } $manifest.Add([pscustomobject]@{ Query = $reportName; Status = 'FailedOrPartial'; RowsProcessed = ''; File = $partialName; Message = $_.Exception.Message }) } } } else { Add-Skipped ($tag + '_GpoSettings') 'Optional full GPO reports were not requested, or the GroupPolicy module could not be loaded. See Errors.csv.' } } } catch { $fatal = $true Add-Failure 'Fatal initialization or local output failure' $_ } finally { # These are exclusively local files. Disk/ACL failures here are terminating. if ($manifest.Count -gt 0) { $manifest | Export-Csv -LiteralPath (Get-ReportPath 'Manifest.csv') -NoTypeInformation -Encoding UTF8 } else { '"Query","Status","RowsProcessed","File","Message"' | Set-Content -LiteralPath (Get-ReportPath 'Manifest.csv') -Encoding UTF8 } if ($failures.Count -gt 0) { $failures | Export-Csv -LiteralPath (Get-ReportPath 'Errors.csv') -NoTypeInformation -Encoding UTF8 } else { '"TimeUtc","Task","Message","ErrorId","Category"' | Set-Content -LiteralPath (Get-ReportPath 'Errors.csv') -Encoding UTF8 } [ordered]@{ ScriptVersion = '1.0'; RunId = $runId StartedUtc = $started.ToString('o'); FinishedUtc = [DateTime]::UtcNow.ToString('o') Computer = $env:COMPUTERNAME Identity = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name PowerShellVersion = $PSVersionTable.PSVersion.ToString() InitialServer = $initialServer; AllForestDomains = [bool]$AllForestDomains IncludeGpoReports = [bool]$IncludeGpoReports SkipGroupMembership = [bool]$SkipGroupMembership FatalFailure = $fatal; ErrorCount = $failures.Count Caveat = 'Successful queries reflect account visibility, not guaranteed completeness. Consult script help.' } | ConvertTo-Json -Depth 4 | Set-Content -LiteralPath (Get-ReportPath 'RunInfo.json') -Encoding UTF8 } Write-Host "Reports: $OutputPath (prefix $runId)" if ($fatal) { throw 'Inventory stopped early. Review the Errors.csv and Manifest.csv files for this run.' } if ($failures.Count -gt 0) { Write-Warning 'Inventory completed with query errors. Review Errors.csv and Manifest.csv.' } else { Write-Host 'Inventory completed. Review Manifest.csv for scope and empty/skipped queries.' }