A spreadsheet named hardware.xlsx, last saved before the summer, is the usual answer to the question of what the network contains. It lists a server retired in spring, misses the two laptops bought in August, and carries the wrong Windows build for half the estate. The script below replaces that file with a repeatable run: a text file of computer names goes in, a CSV and a JSON file come out, and every row carries the processor, memory, local disk size, model and serial number, the exact Windows build, and a count of registered applications. Every dependency ships with Windows, and the notes below cover the parts that usually break on a first attempt.
The Three Data Sources That Answer Most Inventory Questions
Windows exposes inventory facts through three separate mechanisms, and a script that leans on only one of them ends up with gaps it cannot explain.
The first is CIM. Get-CimInstance queries the root/cimv2 namespace and returns typed objects with real properties, so arithmetic works without parsing text: a memory module reports its Capacity in bytes, and dividing 17179869184 by 1GB produces 16. Six classes cover most of the ground. Win32_ComputerSystem and Win32_BIOS supply the model and the serial number, Win32_Processor supplies cores and clock speed, and Win32_LogicalDisk and Win32_OperatingSystem supply disk sizes, the caption, and the build. Win32_PhysicalMemory returns one object per module, which is why the script sums Capacity instead of reading a single value.
The second is Get-ComputerInfo, which wraps dozens of CIM queries into one cmdlet and returns roughly a hundred properties. That convenience has a price. A full call on a healthy desktop takes several seconds because it touches plenty of classes the report never uses, and across four hundred hosts the seconds add up. Get-ComputerInfo is a fine way to look at one machine by hand, and its -Property parameter keeps it usable in a loop. For fleet work, targeted CIM queries win on both speed and control.
The third is the registry, the only practical place to find conventional desktop software. Get-ItemProperty over the two Uninstall keys returns DisplayName, DisplayVersion, Publisher, and InstallDate for anything that registered an uninstaller. The tempting alternative, Win32_Product, forces Windows Installer to validate every MSI package on the machine. That call is slow, writes MsiInstaller events to the application log, and has been known to start repair actions. Running it against a fleet is the kind of decision that produces a help desk queue the next morning.
A single machine can be checked in seconds with a narrowed property list, which is also the quickest way to confirm the build number before trusting a fleet run:
Get-ComputerInfo -Property WindowsProductName, OsVersion, OsBuildNumber,
CsManufacturer, CsModel, BiosSerialNumber
Reading the Computer List and Asking for Credentials Once
The script takes a path rather than an array buried inside the file, because the list is the part that changes. One host name per line, blank lines and lines starting with a hash ignored, duplicates removed after trimming: four pipeline stages turn a hand-edited text file into a clean target set. Fully qualified names beat addresses here, since Kerberos issues tickets for names, and an address can quietly point at a different machine after a lease expires.
Credentials arrive once, as a PSCredential object. Get-Credential prompts in its own window, the password travels as a SecureString, and the object goes to Invoke-Command rather than into the file. A scheduled run cannot answer a prompt, so the account has to come from somewhere else: a group managed service account, or the stored credentials of the task itself. Writing a password into the script or a side file is the shortcut that turns an inventory tool into a security finding.
Three conditions decide whether the first run reaches any host at all:
- The WinRM listener exists on each target and the firewall rule for port 5985 or 5986 is open;
- the account used for collection belongs to the local Administrators group or holds equivalent rights;
- the account that runs the script can write to the output folder and is allowed to run local scripts by execution policy.
Enable-PSRemoting -Force on a target creates the listener, starts the service, and opens the firewall rule in one step, and a domain group policy does the same work at scale. Workgroup machines need more help, because there is no Kerberos trust to lean on: TrustedHosts on the client, or a certificate listener on 5986, plus explicit credentials in every call. Test-WSMan against a few names answers the listener question in a second, long before the collection starts.
The Script and the Collection Block at Its Center
The collector is a script block, and that detail matters. Invoke-Command serializes it, ships it to each host, and runs it in a fresh session there, so $env:COMPUTERNAME reports the target and every CIM query reads the target's own repository. Nothing is copied from the administrator's workstation.
Inside the block, an ordered dictionary holds the row before it becomes an object. Order matters because Export-Csv writes columns in property order, and a stable order makes two exports comparable in a diff tool. Every field starts with a neutral value, so a host that fails halfway still produces the full column set rather than a ragged row that shifts later fields sideways. One try block wraps the CIM calls, and one catch turns a failure into data: a machine with a corrupt repository, a stopped WMI service, or a permissions problem returns a row with Status set to Error and the exception text in ErrorMessage. That row is more useful than silence, because a missing host looks exactly like a host nobody remembered to add to the list.
Three details in the field mapping repay attention. NumberOfCores counts physical cores, while LogicalProcessors counts the threads the scheduler sees, and reporting the wrong one makes a consolidation ratio look strange. The disk query filters on DriveType 3, so mapped network drives and removable media stay out of the total. BuildNumber says 19045 for a current Windows 10 machine, and the caption adds the edition, but neither carries the monthly revision, so the script reads UBR from the CurrentVersion registry key and appends it, producing the four-part number that support cases actually quote.
Software collection reads both Uninstall keys, the native view and the WOW6432Node view where 32-bit installers land. Two filters remove noise: entries without a DisplayName are patches and components, and entries flagged SystemComponent are runtime pieces nobody wants in a software report. What remains becomes a count rather than a full list, because four hundred hosts times two hundred applications is a table nobody opens.
#Requires -Version 5.1
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)][string]$ComputerList,
[System.Management.Automation.PSCredential]$Credential,
[ValidateRange(1, 64)][int]$ThrottleLimit = 16,
[string]$OutputFolder = 'inventory'
)
$ErrorActionPreference = 'Stop'
$names = @(Get-Content -LiteralPath $ComputerList | ForEach-Object { $_.Trim() } |
Where-Object { $_ -and $_ -notmatch '^#' } | Select-Object -Unique)
$collector = {
$row = [ordered]@{
ComputerName = $env:COMPUTERNAME; Status = 'OK'; ErrorMessage = ''
Model = ''; Serial = ''; Cpu = ''; Cores = 0
MemoryGB = 0; DiskGB = 0; OS = ''; Build = ''; Apps = 0
}
try {
$os = Get-CimInstance Win32_OperatingSystem -ErrorAction Stop
$cpu = Get-CimInstance Win32_Processor -ErrorAction Stop | Select-Object -First 1
$ram = Get-CimInstance Win32_PhysicalMemory -ErrorAction Stop
$fixed = Get-CimInstance Win32_LogicalDisk -Filter 'DriveType = 3' -ErrorAction Stop
$row.Model = (Get-CimInstance Win32_ComputerSystem -ErrorAction Stop).Model
$row.Serial = (Get-CimInstance Win32_BIOS -ErrorAction Stop).SerialNumber
$row.Cpu = $cpu.Name.Trim()
$row.Cores = $cpu.NumberOfCores
$row.MemoryGB = [math]::Round((($ram | Measure-Object Capacity -Sum).Sum / 1GB), 1)
$row.DiskGB = [math]::Round((($fixed | Measure-Object Size -Sum).Sum / 1GB), 1)
$row.OS = $os.Caption
$ubr = (Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion').UBR
$row.Build = if ($ubr) { '{0}.{1}' -f $os.BuildNumber, $ubr } else { "$($os.BuildNumber)" }
$keys = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*',
'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*'
$row.Apps = @(Get-ItemProperty -Path $keys -ErrorAction SilentlyContinue |
Where-Object { $_.DisplayName -and -not $_.SystemComponent }).Count
}
catch {
$row.Status = 'Error'
$row.ErrorMessage = $_.Exception.Message
}
[pscustomobject]$row
}
$call = @{ ComputerName = $names; ThrottleLimit = $ThrottleLimit; ErrorAction = 'Continue' }
if ($Credential) { $call.Credential = $Credential }
$records = @(Invoke-Command @call -ScriptBlock $collector -ErrorVariable failed)
foreach ($e in $failed) {
$records += [pscustomobject]@{ ComputerName = $e.TargetObject; Status = 'Not reached' }
}
$columns = 'ComputerName', 'Status', 'Model', 'Serial', 'Cpu', 'Cores',
'MemoryGB', 'DiskGB', 'OS', 'Build', 'Apps', 'ErrorMessage'
$records = @($records | Select-Object -Property $columns)
New-Item -ItemType Directory -Path $OutputFolder -Force | Out-Null
$stamp = Get-Date -Format 'yyyyMMdd-HHmm'
$records | Export-Csv (Join-Path $OutputFolder "inventory-$stamp.csv") -NoTypeInformation
ConvertTo-Json -InputObject @($records) -Depth 3 |
Set-Content (Join-Path $OutputFolder "inventory-$stamp.json")
Called with a credential prompt, the script needs nothing else:
.\Get-FleetInventory.ps1 -ComputerList .\hosts.txt -Credential (Get-Credential) -ThrottleLimit 12
Sending the Block Out with Invoke-Command and Timeouts
A ping sweep or a Test-WSMan loop before the run finds silent addresses faster, but the script leans on the remoting errors instead. Those errors also cover the harder case, a host that answers on the network and refuses the session, and each record names its target. The loop at the end appends one row per failed host, so the output file never quietly loses a machine that was in the input list.
The call splats a hashtable, which keeps the optional credential out of the parameter list when nobody passes one. ThrottleLimit 16 sits at half the default of 32, a deliberate choice: each concurrent session holds a WinRM connection, a runspace, and a slice of the target's query capacity, and halving the default leaves room for the monitoring agent already talking to the same service. ErrorAction Continue keeps one bad host from ending the run, and ErrorVariable keeps a structured copy of every failure so the appended rows can name the machine.
Expect twenty to forty seconds per host, most of it spent in the software registry read. Four hundred hosts at sixteen concurrent sessions works out to about thirteen minutes, which fits inside a maintenance window and does not require a dedicated server. On slow links, New-PSSessionOption with an OpenTimeout of 20000 and an OperationTimeout of 120000 stops a stalled connection from holding a slot for the whole run. The objects that come back also carry PSComputerName, added by remoting, which is why the script names its output columns instead of exporting whatever properties happen to arrive.
Turning Raw Records into CSV and JSON Files
Two output formats answer two different needs. The CSV opens in a spreadsheet, sorts by build number, and feeds a pivot table. The JSON keeps the records with their types intact for whatever consumes them next, and it is the format to choose when a dashboard or another script rather than a person reads the result.
Export-Csv needs -NoTypeInformation, otherwise the first line becomes a type comment that breaks every naive parser downstream. Encoding deserves a thought as well: Windows PowerShell 5.1 defaults Export-Csv to ASCII, so non-Latin characters become question marks; pass -Encoding UTF8 explicitly, which in 5.1 adds a byte order mark that Excel handles and some command line tools do not. PowerShell 7 defaults to UTF-8 without a BOM. Delimiters are another quiet failure, since a machine with a regional list separator of semicolon produces a file that looks correct locally and wrong everywhere else, so the delimiter should be stated explicitly when the output crosses borders.
ConvertTo-Json has two traps. The default depth of 2 truncates nested structures, which is why the script asks for 3. A single record converts to a bare object instead of an array, and a consumer expecting a list fails on the day only one host answers; passing the array with -InputObject keeps the JSON a list, and PowerShell 7 offers -AsArray for the same purpose. Arrays do not survive a CSV column cleanly either, so software detail stays in per-host queries, and the fleet file stays flat. A run against five hundred hosts produces a file in the low hundreds of kilobytes, small enough to keep for a year and awkward enough that nobody should open it in Notepad.
The Weekly Inventory Routine and Its Changes
The first run is a snapshot, and snapshots flatter. The second run is where the tool starts paying for itself, because two files with identical columns can be compared. Hosts present last week and absent this week are the interesting rows: a laptop that has not connected since a repair, a virtual machine removed without a ticket, a server whose remoting configuration drifted. The same comparison on the Apps column flags software that appeared without a change record.
Honesty about limits matters more than another field. Registry entries are not licenses, and a count of two hundred applications says nothing about entitlement. Per-user installs that live under HKCU never appear, because the remote session runs as the service account and not as the person who uses the machine. Store applications registered per user share that blind spot. A host switched off during the window is simply missing, which is why the run should compare its host count against the expected list instead of trusting the row total.
Scheduling is the easy part. A Task Scheduler job at two in the morning, running under an account with the rights described earlier and with transcript logging switched on, needs no attention until the password policy changes. The harder discipline is agreeing what the columns mean and keeping them stable, since a renamed column silently breaks every downstream report.
The script earns its place for a plain reason. It asks the same questions in the same order every week, records what it could not answer, and leaves a file that outlives the administrator who wrote it. That is a lower bar than a configuration management platform and a far higher one than the spreadsheet it replaces.