<# .SYNOPSIS Exports Active Directory computer objects to CSV with the attributes you actually use. .DESCRIPTION Pulls computer accounts from AD and flattens them into one row each: name, OS and build, enabled state, last logon, days since last logon, password age, OU and description. Handy for inventory, audits, and finding stale machines before a cleanup. .PARAMETER SearchBase Only include computers under this OU. Defaults to the whole domain. .PARAMETER CsvPath Output file. Defaults to ad-computers-.csv in the current folder. .PARAMETER EnabledOnly Leave disabled computer accounts out. .PARAMETER IncludeIPAddress Resolve each computer's IPv4 address through DNS. Noticeably slower. .PARAMETER Server Domain or domain controller to query. .PARAMETER PassThru Return the rows as objects as well as writing the CSV. .EXAMPLE .\Export-ADComputerInventory.ps1 .EXAMPLE .\Export-ADComputerInventory.ps1 -SearchBase 'OU=Workstations,DC=contoso,DC=com' -EnabledOnly -PassThru | Where-Object DaysSinceLogon -gt 90 #> [CmdletBinding()] param( [string]$SearchBase, [string]$CsvPath = (Join-Path (Get-Location) ('ad-computers-{0:yyyy-MM-dd}.csv' -f (Get-Date))), [switch]$EnabledOnly, [switch]$IncludeIPAddress, [string]$Server, [switch]$PassThru ) $ErrorActionPreference = 'Stop' Import-Module ActiveDirectory $query = @{ Filter = if ($EnabledOnly) { 'Enabled -eq $true' } else { '*' } Properties = 'CanonicalName', 'Description', 'DNSHostName', 'LastLogonDate', 'OperatingSystem', 'OperatingSystemVersion', 'PasswordLastSet', 'whenCreated', 'ManagedBy' } if ($SearchBase) { $query.SearchBase = $SearchBase } if ($Server) { $query.Server = $Server } if ($IncludeIPAddress) { $query.Properties += 'IPv4Address' } $computers = Get-ADComputer @query $now = Get-Date Write-Verbose "Found $(@($computers).Count) computer objects" $rows = foreach ($pc in $computers) { $row = [ordered]@{ Name = $pc.Name DNSHostName = $pc.DNSHostName Enabled = $pc.Enabled OperatingSystem = $pc.OperatingSystem OSVersion = $pc.OperatingSystemVersion LastLogonDate = $pc.LastLogonDate DaysSinceLogon = if ($pc.LastLogonDate) { [int]($now - $pc.LastLogonDate).TotalDays } else { $null } PasswordLastSet = $pc.PasswordLastSet PasswordAgeDays = if ($pc.PasswordLastSet) { [int]($now - $pc.PasswordLastSet).TotalDays } else { $null } Created = $pc.whenCreated Description = $pc.Description ManagedBy = $pc.ManagedBy OU = ($pc.CanonicalName -replace '/[^/]+$', '') DistinguishedName = $pc.DistinguishedName } if ($IncludeIPAddress) { $row.IPv4Address = $pc.IPv4Address } [pscustomobject]$row } $rows = @($rows | Sort-Object Name) $rows | Export-Csv -Path $CsvPath -NoTypeInformation -Encoding UTF8 Write-Host "Exported $($rows.Count) computers to $CsvPath" if ($PassThru) { $rows }