Powershell: Query Active Directory to list servers by type, OS, and IP Address
In this guide, we will use PowerShell to query Active Directory and retrieve information about servers, including their type (virtual or physical), operating system versions, and IP addresses. The output will be displayed on the console and also saved to a CSV file.
Step 1: Open PowerShell
First, open PowerShell by searching for “PowerShell” in the Start menu or pressing “Windows + X” and selecting “Windows PowerShell” from the menu.
Step 2: Connect to Active Directory
Before querying Active Directory, you need to establish a connection. Use the following command and provide your domain credentials when prompted:
Import-Module ActiveDirectory
$cred = Get-Credential
Connect-ADServer -Credential $cred
Step 3: Query Active Directory for Servers
Now, let’s run a PowerShell script to query Active Directory and retrieve the required information:
$servers = Get-ADComputer -Filter {OperatingSystem -Like "Windows Server*"} -Properties OperatingSystem,OperatingSystemVersion,IPv4Address
The above command will retrieve all computer objects with an operating system that starts with “Windows Server”.
Step 4: Prepare the Output
Next, we’ll format the data to display the server type (virtual or physical), OS version, and IP address:
foreach ($server in $servers) {
$type = if ($server.OperatingSystem -like "*Virtual*") { "Virtual" } else { "Physical" }
$osVersion = $server.OperatingSystemVersion
$ipAddress = $server.IPv4Address
Write-Host "Server Name: $($server.Name), Type: $type, OS Version: $osVersion, IP Address: $ipAddress"
$output = "$($server.Name),$type,$osVersion,$ipAddress"
$output | Out-File -Append -FilePath "C:\ServerList.csv"
}
This code iterates through each server and determines if it’s virtual or physical based on the operating system description. It then prints the server details to the console and appends the information to a CSV file named “ServerList.csv” on your C:\ drive.
Step 5: Run the Script
Copy and paste the entire script into your PowerShell console and press Enter to execute it.
Step 6: Check the Output
After running the script, you will see the server details displayed on the console. Additionally, you can navigate to “C:\” and open the “ServerList.csv” file to view the same information in CSV format.
Congratulations! You have successfully queried Active Directory and listed servers by type, OS version, and IP address.