PowerShell Script Computer Ping Inventory.

By José C. Nieves Pérez


$computers = Get-ADComputer -Filter {OperatingSystem -NotLike «Server«} -SearchBase «DC=******,DC=***» | Select-Object -ExpandProperty Name

$results = foreach ($computer in $computers) {
$ping = Test-Connection -ComputerName $computer -Count 1 -ErrorAction SilentlyContinue
if ($ping) {
$ip = $ping.IPV4Address.IPAddressToString
$rtt = $ping.ResponseTime
} else {
$ip = «N/A»
$rtt = «N/A»
}
[PSCustomObject]@{
ComputerName = $computer
Online = if ($ping) { «Online» } else { «Offline» }
IPAddress = $ip
AvgRTT = $rtt
}
}

$results | Export-Csv -Path «C:\temp\computer-ping-results.csv» -NoTypeInformation


Explanation:

The $ping variable now stores the result of the Test-Connection cmdlet, which includes information about the IP address and round trip time (RTT) of the ping response.

The if statement checks if the ping was successful (i.e., $ping is not $null). If it was, the script retrieves the IP address and RTT from the $ping object. If it wasn’t, the script sets the IP address and RTT to «N/A».

The custom object created by the loop now has two additional properties: «IPAddress» and «AvgRTT». The «IPAddress» property is set to the value of $ip, and the «AvgRTT» property is set to the value of $rtt.

Finally, the $results array is exported to the CSV file as before, but now includes the additional columns for IP address and average round trip time.


Deja un comentario