Resolving hostnames on network using PowerShell

970 views Asked by At
8 | foreach {
    New-Object PSObject -Prop @{
        Address ="192.168.1.$_";
        Status = (Test-Connection "192.168.1.$_" -Quiet -Count 1);
        try {HostName=[System.Net.Dns]::GetHostEntry("192.168.1.$_").HostName} catch {HostName="UNKNOWN"}
    }
} | Format-Table -Auto

I want to resolve the hostnames using [System.Net.Dns]::GetHostEntry(). I am using Test-Connection to get the connection status.

My problem is that when a host name cannot be resolved, the command returns an error. I need to store "UNKNOWN " in the HostName property for that particular member, is there any construct that i can use to achieve this?

1

There are 1 answers

8
BenH On

Put the Try/Catch after you start defining HostName.

8 | foreach {
    new-object psobject -prop @{
        Address = "192.168.1.$_"
        Status = Test-connection "192.168.1.$_" -quiet -count 1
        HostName = Try {[System.Net.Dns]::gethostentry("192.168.1.$_").HostName} Catch {"UNKNOWN"}
    }
} | format-table -auto