test-connections – ping a list of addresses from a csv file and report result.

#test_connections - read a csv list of hosts and ping each one, record success or failure. Does a dns lookup of name
# CSV file format
#  ip_address - ipv4 address for ping and traceroute 
#  Name  - dns lookup will be done on this
#  Description
#

$target=import-csv -path "test_connections_target.csv"

Write-Host -ForegroundColor green "Testing from $($env:computername)."	
$results=@()
foreach ( $t in $target ) {
    $t1=$t.name
    $t2=Resolve-DnsName $t1
    $item= New-Object PSobject 
    
    $item | Add-Member -MemberType NoteProperty -Name 'source' -Value ($env:computername)
    
    $item | Add-Member -MemberType NoteProperty -Name 'IPv4Address' -Value ($t.ip_address)
    $item | Add-Member -MemberType NoteProperty -Name 'Name' -Value ($($t2[0].name))
    $item | Add-Member -MemberType NoteProperty -Name 'Description' -Value ($t.Description)
    $item | Add-Member -MemberType NoteProperty -Name 'GateWay' -Value ("")
    $item | Add-Member -MemberType NoteProperty -Name 'ResponseTime' -Value ("")
            
    $message="$($t.IP_Address), $($t2[0].name), $($t.Description), "
    try { $out1=Test-Connection -ComputerName $t1 -Count 1 -ErrorAction stop
            $message+=" response time, $($out1.responsetime)"
            $item.ResponseTime="$($out1.responsetime)"
            #now do a traceroute
            $out2=Test-NetConnection -computername $($t.IP_Address) -TraceRoute
            if ($out2.TraceRoute.Count -gt 1 ) { 
                $message+=" Gateway $($out2.traceroute[0])"
                $item.GateWay=$out2.TraceRoute[0]
                }
            else
                {
                $message+=" local address"
                $item.GateWay="local"
                }
            Write-Host -ForegroundColor green $message
            $item | Add-Member -MemberType NoteProperty -Name 'Result' -Value ("Success")


        }
    catch {
        $item | Add-Member -MemberType NoteProperty -Name 'Result' -Value ("Fail")
        $message+="**Error** no connection or timeout"
        Write-Host -ForegroundColor Red -BackgroundColor Yellow $message
        #Write-Error $message
          
        }
    $results += $item

}

$dt=Get-Date -Format "yyyyMMdd-hhmmss"
$csv_file="$($env:temp)/$dt-$($env:computername).csv"
write-host "Output for $($results.count) targets written to $csv_file"
$results | Export-Csv -NoTypeInformation -Path $csv_file

#Read-Host "how was that?"

About Jeff Turner

Technical director of Nano Tera Network Solutions.
This entry was posted in Powershell, VBS, VBA and other scripting. and tagged , . Bookmark the permalink.