0
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
  • pipe lining 8 because my mobile is connected on 192.168.1.8 Commented Jan 9, 2017 at 15:52

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

8 Comments

I tried this, it keeps printing UNKNOWN at the end of the table, i want it to store UNKNOWN under HostName
@SrihariHumbarwadi The code should do exactly what you're asking. Please provide evidence.
@SrihariHumbarwadi works here as expected. I defined a var ' $IP = "192.168.1.$_" ' and replaced the 3 occurences of the IP with $IP
8 | foreach {$address="192.168.1.$_";new-object psobject -prop @{Address =$address;Status =(Test-connection $address -quiet -count 1);HostName=try{[System.Net.Dns]::gethostentry($address). HostName} catch {Return UNKNOWN} }}
^ ran this UNKNOWN : The term 'UNKNOWN' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.