请求获取域内运行指定Windows系统的在线服务器主机名与IP地址的PowerShell命令
Hey there! I totally get what you need—you want a clean, focused list of online Windows Server 2012 R2 and 2016 machines in your domain, complete with their hostnames and IP addresses. The problem with just using Get-ADComputer (I think that's what you meant by "Get-Computer"?) on its own is it grabs every machine registered in AD, even those that are powered off or long decommissioned. Let's fix that with a targeted script that combines AD filtering with online checks:
# Define the target Windows Server versions we're targeting $targetOperatingSystems = @("Windows Server 2012 R2*", "Windows Server 2016*") # Fetch matching AD computers, filter for online ones, and output key details Get-ADComputer -Filter {OperatingSystem -like $targetOperatingSystems[0] -or OperatingSystem -like $targetOperatingSystems[1]} ` -Properties OperatingSystem, IPv4Address | Where-Object { Test-Connection -ComputerName $_.Name -Count 1 -Quiet -ErrorAction SilentlyContinue } | Select-Object Name, IPv4Address, OperatingSystem | Sort-Object OperatingSystem, Name
Let's break down what each part does:
Get-ADComputer: Queries Active Directory to pull only computers where the operating system matches either Windows Server 2012 R2 or 2016. We explicitly request theIPv4AddressandOperatingSystemproperties since they aren't included in the default output.Where-Object { Test-Connection ... }: Filters out any machines that don't respond to a quick 1-packet ping. The-Quietflag keeps output clean, and-ErrorAction SilentlyContinuesuppresses annoying error messages for machines that are no longer reachable but still in AD.Select-Object: Narrows the results down to just the information you care about: hostname (Name), IP address (IPv4Address), and OS version.Sort-Object: Organizes the final list neatly by OS version first, then hostname, making it easier to scan.
Quick tweak if needed:
If some of your servers have multiple IPv4 addresses, the IPv4Address field might show an array. To combine them into a single comma-separated string, adjust the Select-Object line like this:
Select-Object Name, @{Name='IPv4Address'; Expression={$_.IPv4Address -join ', '}}, OperatingSystem
备注:内容来源于stack exchange,提问作者Vidarsskjalf

