Windows to Linux Migration Series 2: Building a Complete Windows Server Inventory (PowerShell and a Workload Map)

Windows to Linux Migration Series: Part 2. Previous: Part 1: Overview and Planning. Next up: part 3, assessing each workload (fit, replace, rewrite or retain). The whole series is under the windows-to-linux-migration tag.

Part 1 said the most common reason a Windows-to-Linux migration goes wrong is that nobody knew everything the old servers did. This part is the fix: a repeatable inventory of every Windows server, collected with PowerShell, saved as files you can diff, and turned into a workload map. The map is the input to every later decision in the series: what to replace, what to rewrite, what has to coexist for a while, and in what order to cut over.

Applies to: Windows Server 2012 R2 through 2025 as the source (Windows PowerShell 5.1, which those releases include), with the collected data processed on an AlmaLinux 10 or RHEL 10 admin host. Older servers (2008 R2) lack several of the cmdlets below; a note at the end covers them. Nothing here changes a server: every command only reads.

Prerequisites

  • An account that is a local administrator on the servers you will inventory (some data, such as scheduled tasks for all users and certificates, is only visible to admins).
  • PowerShell remoting (WinRM) enabled on the targets, which is the default on Windows Server 2012 and later in a domain. The older post Enable Remote PowerShell Access covers turning it on.
  • A list of server names to start from. AD can give you one (below), but also ask the virtualization and network teams: a server that is not domain-joined will not show up in AD.
  • A share or folder to collect results in, and an AlmaLinux host with python3 and git to keep and compare them.
  • Permission from whoever owns the servers. Inventory is read-only, but running scripts across production should still be a known change.

What to collect, and why

AreaWhy it matters for the migrationSource
OS version, hardware, uptime, domainSupport dates, sizing of the Linux replacementGet-CimInstance Win32_OperatingSystem, Win32_ComputerSystem
Installed roles and featuresThe main workloads: AD DS, DNS, DHCP, File, Print, IIS, RDS, WSUS, Hyper-VGet-WindowsFeature
Installed softwareLine-of-business apps, agents, SQL Server, backup clientsUninstall registry keys
Services set to start automaticallyWhat actually runs, including third-party servicesGet-CimInstance Win32_Service
Scheduled tasksThe hidden jobs: exports, FTP pushes, cleanup scriptsGet-ScheduledTask
Listening ports and established connectionsWho talks to this server, and who it depends onGet-NetTCPConnection
Shares and printersFile and print workloads, permissions to recreate on Samba and CUPSGet-SmbShare, Get-Printer
CertificatesExpiry dates and services bound to them (IIS, RDP, LDAPS)Cert:\LocalMachine\My
IP configuration and DNSAddresses to keep, DNS records to moveGet-NetIPConfiguration
Local users and groupsService accounts and local admins that must exist on the new sideGet-LocalUser, Get-LocalGroupMember

Step 1: Build the server list from AD

PS C:\> Get-ADComputer -Filter 'OperatingSystem -like "*Windows Server*" -and Enabled -eq $true' `
           -Properties OperatingSystem, OperatingSystemVersion, LastLogonDate, IPv4Address |
         Select-Object Name, DNSHostName, OperatingSystem, OperatingSystemVersion, IPv4Address, LastLogonDate |
         Export-Csv C:\inventory\servers-ad.csv -NoTypeInformation

Review the CSV by hand. Remove servers that are already gone (old LastLogonDate), and add any non-domain servers you know about.

Step 2: The per-server inventory script

Save this as Get-ServerInventory.ps1. It returns one object per server with nested lists, and the caller writes it to JSON so nested data survives:

# Get-ServerInventory.ps1 - read-only inventory of one Windows server
$os  = Get-CimInstance Win32_OperatingSystem
$cs  = Get-CimInstance Win32_ComputerSystem

$features = @()
if (Get-Command Get-WindowsFeature -ErrorAction SilentlyContinue) {
    $features = Get-WindowsFeature | Where-Object Installed |
                Select-Object Name, DisplayName, FeatureType
}

$uninstall = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*',
             'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*'
$software = Get-ItemProperty $uninstall -ErrorAction SilentlyContinue |
            Where-Object DisplayName |
            Select-Object DisplayName, DisplayVersion, Publisher, InstallDate

$services = Get-CimInstance Win32_Service |
            Where-Object { $_.StartMode -eq 'Auto' } |
            Select-Object Name, DisplayName, State, StartName, PathName

$tasks = Get-ScheduledTask | Where-Object { $_.TaskPath -notlike '\Microsoft\*' } |
         ForEach-Object {
            [pscustomobject]@{
              Name    = $_.TaskName
              Path    = $_.TaskPath
              State   = [string]$_.State
              RunAs   = $_.Principal.UserId
              Actions = ($_.Actions | ForEach-Object { "$($_.Execute) $($_.Arguments)" }) -join '; '
            } }

$listen = Get-NetTCPConnection -State Listen |
          Select-Object LocalAddress, LocalPort,
            @{n='Process';e={(Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue).ProcessName}} |
          Sort-Object LocalPort -Unique

$peers = Get-NetTCPConnection -State Established |
         Where-Object { $_.RemoteAddress -notin '127.0.0.1','::1' } |
         Select-Object RemoteAddress, RemotePort, LocalPort,
           @{n='Process';e={(Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue).ProcessName}}

$shares = Get-SmbShare -Special $false -ErrorAction SilentlyContinue |
          Select-Object Name, Path, Description
$printers = Get-Printer -ErrorAction SilentlyContinue |
            Select-Object Name, DriverName, PortName, Shared, ShareName
$certs = Get-ChildItem Cert:\LocalMachine\My |
         Select-Object Subject, Issuer, Thumbprint,
           @{n='NotAfter';e={$_.NotAfter.ToString('s')}},
           @{n='DnsNames';e={($_.DnsNameList | ForEach-Object Unicode) -join ','}}

[pscustomobject]@{
  Computer    = $env:COMPUTERNAME
  Collected   = (Get-Date).ToString('s')
  OS          = $os.Caption
  Version     = $os.Version
  LastBoot    = $os.LastBootUpTime.ToString('s')
  Domain      = $cs.Domain
  Model       = "$($cs.Manufacturer) $($cs.Model)"
  MemoryGB    = [math]::Round($cs.TotalPhysicalMemory/1GB,1)
  CPUs        = $cs.NumberOfLogicalProcessors
  Disks       = Get-CimInstance Win32_LogicalDisk -Filter 'DriveType=3' |
                Select-Object DeviceID, @{n='SizeGB';e={[math]::Round($_.Size/1GB)}},
                                        @{n='FreeGB';e={[math]::Round($_.FreeSpace/1GB)}}
  IP          = Get-NetIPConfiguration | Select-Object InterfaceAlias,
                  @{n='IPv4';e={$_.IPv4Address.IPAddress -join ','}},
                  @{n='DNS';e={$_.DNSServer.ServerAddresses -join ','}}
  Features    = $features
  Software    = $software
  Services    = $services
  Tasks       = $tasks
  Listening   = $listen
  Peers       = $peers
  Shares      = $shares
  Printers    = $printers
  Certificates= $certs
  LocalAdmins = Get-LocalGroupMember -Group Administrators -ErrorAction SilentlyContinue |
                Select-Object Name, ObjectClass, PrincipalSource
}

Notes on choices in the script. Installed software is read from the uninstall registry keys rather than Win32_Product, because querying Win32_Product is slow and makes Windows Installer run a consistency check on every MSI package it lists. Scheduled tasks under \Microsoft\ are Windows’ own and are skipped. Established connections are a snapshot; a nightly job that connects for two minutes at 02:00 will not appear, which is why the script is run more than once (step 4).

Step 3: Run it across the estate

PS C:\> $servers = (Import-Csv C:\inventory\servers-ad.csv).DNSHostName
PS C:\> $stamp = Get-Date -Format yyyyMMdd-HHmm
PS C:\> Invoke-Command -ComputerName $servers -FilePath C:\inventory\Get-ServerInventory.ps1 `
          -ErrorAction SilentlyContinue -ErrorVariable failed |
        ForEach-Object {
          $_ | ConvertTo-Json -Depth 5 |
            Set-Content -Encoding UTF8 "C:\inventory\raw\$($_.Computer)-$stamp.json"
        }
PS C:\> $failed | ForEach-Object { $_.TargetObject } | Sort-Object -Unique |
          Set-Content C:\inventory\unreachable-$stamp.txt

Invoke-Command runs the script on the remote servers in parallel (32 at a time by default; -ThrottleLimit changes that). The list of unreachable servers is as important as the results: each one is either gone, not domain-joined, or blocking WinRM, and someone has to find out which.

Role-specific details are worth one extra command each where the role exists:

# DNS server: zones to move
Get-DnsServerZone | Select-Object ZoneName, ZoneType, IsDsIntegrated, IsReverseLookupZone
# DHCP server: scopes and reservations
Get-DhcpServerv4Scope | Select-Object ScopeId, Name, StartRange, EndRange, LeaseDuration
Get-DhcpServerv4Scope | Get-DhcpServerv4Reservation
# IIS (Windows Server 2016+ with the IISAdministration module)
Get-IISSite | Select-Object Name, State, @{n='Bindings';e={$_.Bindings.BindingInformation -join ' '}}
# SQL Server instances on this host
Get-Service -Name 'MSSQL*' | Select-Object Name, Status, StartType

For SQL Server, the database list per instance comes from the older post Find Database Names Microsoft SQL Server; part 3 decides whether those databases move to PostgreSQL or stay on SQL Server.

Step 4: Keep the results in git on the Linux admin host

Copy the raw folder to the AlmaLinux admin host (an SMB mount or scp from a Windows OpenSSH client both work) and commit it. Run the collection again in a week and at month end; git diff shows new services, tasks and connections you missed the first time:

[admin@alma10 ~]$ mkdir -p ~/win-inventory && cd ~/win-inventory && git init -q
[admin@alma10 win-inventory]$ cp /mnt/inventory/raw/*.json raw/ && git add raw && git commit -qm "inventory 20261204"
[admin@alma10 win-inventory]$ git log --oneline | head -3
4f2a9c1 inventory 20261204

Step 5: Turn raw data into a workload map

A short Python script flattens the JSON into one CSV row per server with the facts that drive decisions. Windows PowerShell 5.1 writes UTF-8 with a byte-order mark, hence utf-8-sig:

#!/usr/bin/python3
# workload_map.py - one row per server from the latest JSON per host
import json, glob, csv, os, collections

latest = {}
for f in sorted(glob.glob('raw/*.json')):
    host = os.path.basename(f).rsplit('-', 2)[0]
    latest[host] = f            # sorted names: the last file is the newest

def as_list(x):
    return x if isinstance(x, list) else ([x] if x else [])

rows = []
for host, f in sorted(latest.items()):
    d = json.load(open(f, encoding='utf-8-sig'))
    feats = [x['Name'] for x in as_list(d.get('Features'))
             if x.get('FeatureType') == 'Role']
    rows.append({
        'server': host,
        'os': d.get('OS'),
        'roles': ' '.join(feats),
        'auto_services_outside_windows_dir': sum(1 for s in as_list(d.get('Services'))
                                    if 'Windows' not in (s.get('PathName') or '')),
        'custom_tasks': len(as_list(d.get('Tasks'))),
        'shares': len(as_list(d.get('Shares'))),
        'printers': len(as_list(d.get('Printers'))),
        'listening_ports': ' '.join(sorted({str(p['LocalPort']) for p in as_list(d.get('Listening'))}, key=int)),
        'certs_expiring': ' '.join(c['Subject'] for c in as_list(d.get('Certificates'))
                                   if c.get('NotAfter','') < '2027-07-01'),
    })

with open('workload-map.csv', 'w', newline='') as out:
    w = csv.DictWriter(out, fieldnames=rows[0].keys())
    w.writeheader(); w.writerows(rows)
print(len(rows), 'servers written to workload-map.csv')
[admin@alma10 win-inventory]$ python3 workload_map.py
23 servers written to workload-map.csv
[admin@alma10 win-inventory]$ column -s, -t < workload-map.csv | head -4
server  os                                   roles                       auto_services_outside_windows_dir  custom_tasks ...
DC1     Microsoft Windows Server 2019 ...    AD-Domain-Services DNS DHCP 3                     1
FS1     Microsoft Windows Server 2016 ...    FileAndStorage-Services     5                     4

Dates are written as sortable strings (ToString('s')) in the PowerShell script because Windows PowerShell 5.1 would otherwise serialize them as /Date(...)/ values, which is why the certificate check can compare them as text. The service count is a rough filter (services whose binary is outside the Windows directory), meant to point you at third-party software, not to be exact. The numbers in the sample output are illustrative, not from a real estate.

Then add columns by hand that no script can fill: business owner, who uses it, when it may be down, and the dependencies you learned from the Peers data and from interviews. That finished sheet is the workload map.

Verification checklist

  • Every server in the AD list has a JSON file or is listed in unreachable with a reason.
  • Non-domain servers from the virtualization and network inventories were added and inventoried.
  • At least two collection runs a week or more apart are in git, and the diff was reviewed.
  • Every role in the map has an owner, and every custom scheduled task has a known purpose.
  • Expiring certificates and the services that use them are listed; they are often the first hard deadline.

Troubleshooting

ProblemFix
Connecting to remote server ... failed: WinRM cannot complete the operationWinRM not enabled or blocked by firewall. Test-WSMan server1; enable with Enable-PSRemoting on the target.
Get-WindowsFeature not recognizedNot a server SKU, or very old OS. The script skips it; record roles by hand.
Empty Tasks or CertificatesThe account is not a local administrator on that server.
JSON shows System.Object[] in places-Depth too low. Raise ConvertTo-Json -Depth.
Python UnicodeDecodeError or JSON error at char 0Byte-order mark. Open with encoding='utf-8-sig' as in the script.
Windows Server 2008 R2 hostsGet-ScheduledTask, Get-NetTCPConnection, Get-SmbShare and Get-Printer do not exist there. Use schtasks /query /fo csv /v, netstat -ano, Get-WmiObject Win32_Share and Win32_Printer.

Where this fits in the series

Part 3 takes the workload map and applies a fit / replace / rewrite / retain decision to each workload: AD, file and print, Exchange, SQL Server, IIS and .NET, SharePoint, RDS and line-of-business applications. The companion Windows and Linux Integration Series covers running Linux alongside AD during the long coexistence period; its part 2 and part 3 are useful before any Linux server joins the domain. The older post Get Windows Server Statistics shows a quick single-server view.

Windows to Linux Migration Series: Part 2. Previous: Part 1: Overview and Planning. Next: part 3, assessing each workload.

References: Microsoft Learn documentation for Get-CimInstance, Get-WindowsFeature, Get-ScheduledTask, Get-NetTCPConnection, Get-SmbShare, Get-Printer, Invoke-Command, ConvertTo-Json, Get-DnsServerZone, Get-DhcpServerv4Scope and Get-IISSite; Microsoft support guidance on why Win32_Product should not be used for software inventory.

Leave a Reply

Your email address will not be published. Required fields are marked *