Solved

powershell script to ping, save IP as variable, use that variable to do a nbstat and output to file

Posted on 2014-12-09
11
965 Views
Last Modified: 2014-12-16
hi all

brand new to powershell so i have a steep learning curve.
i need a script that will ping a list of servers from a txt file... it will then save the IP of that server and run a nbtstat -a to make sure dns is correct or not.

maybe theres certain cmdlets that will do this for me?

so far i have come up with the following script which does ping the servers, fails on the ones that arent live any more.. but it doesnt check the dns.
so if the dns is still around for a particular server it will actually come back with a IP reference

Test-Connection -computer (get-content c:\temp2\servers.txt) -count 1| Select Address,IPv4Address

Open in new window


here is what the output looks like so far
so server2 no longer exists but the dns entry is still there... when you do a nbtstat -a on its IP it doesnt find the host.
but a normal ping does find dns entry...

server1                                                                                                                             xxx.xxx.xx.xxx                                                                                                                   
server2                                                                                                                             xxx.xxx.xx.xxx                                                                                                                  
server3                                                                                                                         	xxx.xxx.xx.xxx                                                                                                                 
server4                                                                                                                         	xxx.xxx.xx.xxx                                                                                                                  
server5                                                                                                                    			xxx.xxx.xx.xxx                                                                                                                   
Test-Connection : Testing connection to computer 'server6' failed: Error due to lack of resources
At line:1 char:16
+ Test-Connection <<<<  -computer (get-content c:\temp2\servers.txt) -count 1| Select Address,IPv4Address
    + CategoryInfo          : ResourceUnavailable: (server:String) [Test-Connection], PingException
    + FullyQualifiedErrorId : TestConnectionException,Microsoft.PowerShell.Commands.TestConnectionCommand

Open in new window


so my query is.. what do i do to save the IP of server2 as a variable and then run another command to do nbstat -a or a command equivalent in powershell...


let me know if you need any more details..


many thanks!
0
Comment
Question by:mishcondereya
  • 6
  • 5
11 Comments
 
LVL 39

Expert Comment

by:footech
ID: 40489658
What is in your text file, server names or IP addresses?

I wouldn't rely on nbtstat if I could help it as you'd have to parse the text output.

I'm not sure if I understand what your goal is.  Is it to verify that a DNS record is correct?
If so, I would approach this first by making sure DNS scavenging and possibly DHCP settings are configured in an optimal fashion.
0
 

Author Comment

by:mishcondereya
ID: 40490822
txt file has server names in it. one server per line...

my goal is to see if a server that i can ping actually resolves a host name
as mentioned above there are old entries that return a ping but they are pointing to another server
dns is a total mess here and as far as i know scavenging is not turned on (no idea why not) therefore theres a lot of old legacy dns entries in there that need to be removed.

its quite possible that my approach is the wrong way to do this... so thats why im trying to figure out if powershell is the best solution.
0
 
LVL 39

Expert Comment

by:footech
ID: 40492065
So, yes you do want to make sure that DNS records are correct for a list of machines.

I would follow this guide to get DNS scavenging enabled.
http://blogs.technet.com/b/networking/archive/2008/03/19/don-t-be-afraid-of-dns-scavenging-just-be-patient.aspx
There's a period after enabling scavenging on a zone (but before you have set the server to actually scavenge records), when you'll be checking to make sure that machines are refreshing their records.

The following script pretty much does what you asked for.  It pings a list of machines, then does an additional check to see if the machine is who DNS thinks it is.  I think the most reliable way of checking this last bit is to actually connect to the machine and then have it report back what it thinks its name is.  To connect with Get-WmiObject you need the proper permissions though.
Get-Content file.txt | ForEach `
{
    $name = $_
    $testResponse = Test-Connection -ComputerName $name -Count 1 -ErrorAction SilentlyContinue
    If ( $testResponse.StatusCode -eq 0 )
    {
        $IP = $testResponse.IPV4Address
        # I think we could use any WMI class in the following command as the PSComputerName property is dynamically added
        $returnedName = Get-WmiObject Win32_OperatingSystem -ComputerName $IP | Select -ExpandProperty PSComputerName
        If ( $name -eq $returnedName )
        { Write-Output "DNS record matches contacted computer: $name" }
        Else
        { Write-Output "DNS record does not match contacted computer: $name -- $returnedName" }
    }
}

Open in new window

0
 

Author Comment

by:mishcondereya
ID: 40493518
many thanks for your help, i just tried to run the script and i got a access denied with the get-wmiobject

Get-WmiObject : Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))

Open in new window


which doesnt surprise me, im fairly new here trying to fix things up and my access isnt up to scratch yet...
but i will work on that and get back to you asap with how your script works...


cheers!
0
 
LVL 39

Expert Comment

by:footech
ID: 40493600
I did a quick test of the script before I posted it.  You should be good as soon as you get administrator permissions on the servers.
0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 

Author Comment

by:mishcondereya
ID: 40493952
i ran the script on 2 servers that i definitely have admin access to...
these are 2 that ive been working on ..
i added them to my servers.txt file

and i get the following errors


Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
At line:9 char:38
+         $returnedName = Get-WmiObject <<<<  Win32_OperatingSystem -ComputerName $IP | Select -ExpandProperty PSComputerName
    + CategoryInfo          : InvalidOperation: (:) [Get-WmiObject], COMException
    + FullyQualifiedErrorId : GetWMICOMException,Microsoft.PowerShell.Commands.GetWmiObjectCommand
 
DNS record does not match contacted computer: server1 -- 
Select-Object : Property "PSComputerName" cannot be found.
At line:9 char:87
+         $returnedName = Get-WmiObject Win32_OperatingSystem -ComputerName $IP | Select <<<<  -ExpandProperty PSComputerName
    + CategoryInfo          : InvalidArgument: (\\server2\roo...eratingSystem=@:PSObject) [Select-Object], PSArgumentException
    + FullyQualifiedErrorId : ExpandPropertyNotFound,Microsoft.PowerShell.Commands.SelectObjectCommand
 
DNS record does not match contacted computer: server2 -- 

Open in new window

0
 
LVL 39

Expert Comment

by:footech
ID: 40493996
Looks like a firewall issue.  Be sure to allow DCOM traffic.
0
 

Author Comment

by:mishcondereya
ID: 40494353
right...so i ran the script from a server and it worked!

it showed an error from the dns records that were incorrect...
says access denied and then said

DNS record does not mach contacted computer: servername


i will do a few more tests with other servers before running it on our whole fleet


thanks for your help so far!

will post back tomorrow
0
 
LVL 39

Accepted Solution

by:
footech earned 500 total points
ID: 40496569
Well, access denied shouldn't equate with incorrect DNS.  Here's a modification to handle that error.
Get-Content file.txt | ForEach `
{
    $name = $_
    $testResponse = Test-Connection -ComputerName $name -Count 1 -ErrorAction SilentlyContinue
    If ( $testResponse.StatusCode -eq 0 )
    {
        $IP = $testResponse.IPV4Address
        try {
            # I think we could use any WMI class in the following command as the PSComputerName property is dynamically added
            $returnedName = Get-WmiObject Win32_OperatingSystem -ComputerName $IP | Select -ExpandProperty PSComputerName
            If ( $name -eq $returnedName )
            { Write-Output "DNS record matches contacted computer: $name" }
            Else
            { Write-Output "DNS record does not match contacted computer: $name -- $returnedName" }
        }
        catch {
            Write-Host "Error querying server for name: $name`n$_" -ForegroundColor Red
        }
    }
}

Open in new window

0
 

Author Comment

by:mishcondereya
ID: 40502683
many thanks for the updated script.

looks like its giving me the details that i need... very helpful where it shows that DNS is not matching and then shows which server its actually pinging.


i think thats it for this scripting request..
thanks for your help .. life saver!
0
 

Author Closing Comment

by:mishcondereya
ID: 40502684
perfect
0

Featured Post

Optimizing Cloud Backup for Low Bandwidth

With cloud storage prices going down a growing number of SMBs start to use it for backup storage. Unfortunately, business data volume rarely fits the average Internet speed. This article provides an overview of main Internet speed challenges and reveals backup best practices.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

The article will show you how you can maintain a simple logfile of all Startup and Shutdown events on Windows servers and desktops with PowerShell. The script can be easily adapted into doing more like gracefully silencing/updating your monitoring s…
In this previous article (https://oddytee.wordpress.com/2016/05/05/provision-new-office-365-user-and-mailbox-from-exchange-hybrid-via-powershell/), we made basic license assignments to users in O365. When I say basic, the method is the simplest way …
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

863 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now