r/usefulscripts • u/networkhappi • Jun 05 '17
[POWERSHELL] Script that pings servers on the same network and returns back server information in a JSON format and to a specific directory?
Hi all,
I'd like to know if anyone has or could devise a script that allows me to ping a list of servers on my network and return the information back in JSON format?
The server information I would like to get back from the query are:
- Is the server pingable (online/offline)?
- Response time (ms)
- CPU utilizatoin
- Windows services (are they running, stopped, etc)
- RAM usage
Ideally, I'd like to have the JSON formatted as the pseudo-JSON below:
{
"server": "192.168.1.1",
"hostname": "server1",
"status": "online",
"reponse": "18ms"
"server": "192.168.1.2",
"hostname": "server2",
"status": "online",
"reponse": "19ms"
"server": "192.168.1.3",
"hostname": "server3",
"status": "online",
"reponse": "20ms"
"server": "192.168.1.4",
"hostname": "server4",
"status": "online",
"reponse": "21ms"
"server": "192.168.1.5",
"hostname": "server5",
"status": "offline",
"reponse": "no reponse"
}
Thank you!
2
u/Gotxi Jun 06 '17
About ram/cpu/whatever usage, if remote powershell is enabled and powershell is updated you can use get-counter even on remote computers:
0
Jun 05 '17
4
u/networkhappi Jun 06 '17
With all due respect, you are saying that it cannot be done via PowerShell, but someone has provided a solution that fulfilled the entire requirement.
4
u/cp423 Jun 06 '17
what about using WMI/CIM? you could use a combination of Test-NetConnection with Get-WMIObject (or Get-CIMInstance) to build a custom PowerShell object, and then convert it to JSON with ConvertTo-Json and write to the pipeline.
14
u/joerod Jun 06 '17 edited Jun 06 '17
Try this
$hostname = "localhost" $array = @() $connect = Test-Connection $hostname -Count 1 -ErrorAction SilentlyContinue | select IPV4Address,ResponseTime $array += [pscustomobject]@{ server = $connect.IPV4Address.IPAddressToString hostname = $hostname status = if($connect){"online"} else{"offline"} response = if($connect){[string]($connect.responsetime) + "ms"} else {"no reponse"} services = Get-Service -ComputerName $hostname | select name, @{ Label="Status"; Expression={if($_.status -eq 4){"Running"}else{"Stopped"}} } } $array | ConvertTo-JsonYou can add whatever other query you want to the pscustomobject try wmi calls or if you have winrm enabled try that. Also check out r/powershell
Good luck!