1

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.

2 Answers 2

1

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.

1
1

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.

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .