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
1,235 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 5
11 Comments
 
LVL 40

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 40

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
Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

 

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 40

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
 

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 40

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 40

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

Are You Headed to Black Hat USA 2017?

Getting ready for Black Hat next week? Kick things off with the WatchGuard Badge Challenge and test your puzzle and cipher skills. Do you have what it takes to earn our limited edition Firebox Badge? Get started today - https://crimsonthorn.net

Question has a verified solution.

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

The following article is intended as a guide to using PowerShell as a more versatile and reliable form of application detection in SCCM.
In previous parts of this Nano Server deployment series, we learned how to create, deploy and configure Nano Server as a Hyper-V host. In this part, we will look for a clustering option. We will create a Hyper-V cluster of 3 Nano Server host nodes w…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

631 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