Gateway to PowerShell Scripting
One of the admins on my team asked the question to me, “How would I get the gateway information from a list of servers?”
I stopped to ponder this issue, and immediately said, “WMI queries is the way I would do this.”
The Thought Process to Select WMI
In my environment PowerShell remoting isn’t configured everywhere, so it wouldn’t be a good option.
As it would error (see above) about the WinRM service failed instead of gathering the required information. So the next best is WMI, as it is accepted everywhere, like VISA. So after checking on the WMI classes to gather the gateway, I put together a simple little script to pull the info and put it in to a CSV.
$results = @() $Servers = Get-content C:\scripts\logs\Server_to_Get_Gateway_Information.txt foreach ($Server in $Servers){ $line = "" | Select ServerName, Gateway $line.Servername = $Server $line.Gateway = ((Get-WmiObject Win32_NetworkAdapterConfiguration -ComputerName $Server | Where DefaultIPGateway -ne $Null).DefaultIPGateway) -join ', ' $results += $line } $results | Export-Csv C:\scripts\logs\Servers_with_Gateway_information.csv -NoTypeInformation -UseCulture
So there it is.
The Script Break Down
As with most data collection scripts, you need a place to put the information that you are collecting, here we are using $Results. So we make it a blank array.
$results = @()
Next get the content of the list of servers that needs this to be performed on.
$Servers = Get-content C:\scripts\logs\Server_to_Get_Gateway_Information.txt
Now to step through that list of servers one at a time.
foreach ($Server in $Servers){
Setup a new array and format for the data that I’ll be collecting.
$line = "" | Select ServerName, Gateway
Populate the new array with the required data.
$line.Servername = $Server $line.Gateway = ((Get-WmiObject Win32_NetworkAdapterConfiguration -ComputerName $Server | Where DefaultIPGateway -ne $Null).DefaultIPGateway) -join ', '
Finish by putting one array into the other array.
$results += $line
Close the loop and export the final array to a CSV file.
} $results | Export-Csv C:\scripts\logs\Servers_with_Gateway_information.csv -NoTypeInformation -UseCulture
Make sure to use the switch -NoTypeInformation as this will prevent the first line in the CSV from being a garage line.
-Stuart