Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

I'd appreciate your efforts in helping me modifying the script below so that it can check & convert the list of IPAddress and hostname into something like:

DomainController1 - 10.1.1.10 - UP 
CoreGatewayRTR1 - 10.1.1.254 - DOWN 
JohnPC01 - NO-IP-Address - DOWN 
LindaLaptop02 - 10.1.1.234 - DOWN 
. 
. 
. 

it is a challenge for me to convert IP to DNSName and DNSName to IP then check the online status based on Ping,

the following is the script that I can come up with so far:

$computers= gc C:\ListOfDevices.txt
foreach ($computername in $computers) {
    $DNS = [System.Net.Dns]::GetHostEntry($ComputerName)
    $HostName = $DNS.HostName
    $IP = $DNS.AddressList

   Trap { Continue }
   if (Test-Connection $DNS -erroraction SilentlyContinue -Count 1 ) {
     write-host "$Hostname - $IP - UP" -ForegroundColor GREEN
   }
   else {
     write-host "$Hostname - $IP - DOWN" -ForegroundColor RED
   }
 }

However, the above script still got minor logic error as follows:

  1. all of the result is always displayed as down ?

  2. some of the result is always duplicated even though the IP address of that particular host is only one ?

Any kind of help would be greatly appreciated.

Thanks.

share|improve this question

2 Answers 2

up vote 1 down vote accepted

Your script is failing because the $DNS variable doesn't contain the DNS Name. And you are sending it to the if.

You should send $Hostname to the if.

With this code it will work:

$computers= gc C:\ListOfDevices.txt
foreach ($computername in $computers) {
    $DNS = [System.Net.Dns]::GetHostEntry($ComputerName)
    $HostName = $DNS.HostName
    $IP = $DNS.AddressList

   Trap { Continue }

   if (Test-Connection $HostName -erroraction SilentlyContinue -Count 1) {
     write-host "$Hostname - $IP - UP" -ForegroundColor GREEN
   }
   else {
     write-host "$Hostname - $IP - DOWN" -ForegroundColor RED
   }
 }

And you will get an output like this: Result

You have another issue in your code that maybe you haven't seen. Due the way you define the $Hostname variable it wont be change when the DNS name isn't correct. Check it an define it using another technique.

share|improve this answer
    
Yes it works man ! –  Server System Specialist Dec 8 '11 at 0:34

You might want to add -quiet to the end of your test-connection condition so that it only returns a Boolean. You get a lot more data other than $true or $false if you do it that way.

share|improve this answer
    
Cool, thanks for the suggestion mate ! –  Server System Specialist Dec 8 '11 at 0:34

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.