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?

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328

1 Answers1

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
BenH
  • 9,766
  • 1
  • 22
  • 35
  • I tried this, it keeps printing UNKNOWN at the end of the table, i want it to store UNKNOWN under HostName – Srihari Humbarwadi Jan 09 '17 at 16:33
  • @SrihariHumbarwadi The code should do exactly what you're asking. Please provide evidence. – Ansgar Wiechers Jan 09 '17 at 16:39
  • @SrihariHumbarwadi works here as expected. I defined a var ' $IP = "192.168.1.$_" ' and replaced the 3 occurences of the IP with $IP –  Jan 09 '17 at 16:59
  • 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} }} – Srihari Humbarwadi Jan 09 '17 at 17:03
  • ^ 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. – Srihari Humbarwadi Jan 09 '17 at 17:05
  • @SrihariHumbarwadi Where do you see a `return` in BenH's answer? Please do not get creative. – Ansgar Wiechers Jan 09 '17 at 17:16
  • @SrihariHumbarwadi The `return` is unnecessary. Your issue is that your `UNKNOWN` does not have quotation marks around it, which is necessary for it to be returned as a string. – BenH Jan 09 '17 at 18:07
  • @BenH ok I tried without return. But without quotation marks I'll run it with quotes and let you know – Srihari Humbarwadi Jan 09 '17 at 19:13