Monday, July 29, 2013

Powershell Scripting Techniques : Using While in the Scripts to wait for Network Connection to be Establish.

Hi,
In any scripting language, the one of the  important things are techniques.
You can call it scripting techniques.
Sometime when you are writing scripts, there are some  certain problems come , and to solve them we need to add a special logics and special techniques to handle them.
Same thing was happen to me, i was writing a script and that script has to run every time users logon, and that script require a server to be available before running the script.
Flow Chart.
The logic is something like below flowchart.
Flow
How i solve it.
I solved it using WHILE  script code.
I have added Comments to the below script code, which make it self explanatory.
# Setting bit as False First
$bit = $false
# running while.
while ( $bit -eq $false ) 
        
        {
        # just a notification
        Write-Host 'Checking Internet Connection.' -ForegroundColor 'Yellow'
        
        # Testing Network Connection and storing it in to a vraible
        # when we use -QUIET Parameter with Test-Connection, it stored the value in 
        # true or false
        $testInternetConnectivity = Test-Connection -Count 3 "www.google.com" -Quiet    
        
        # Test-Connection CMDLET return output in TRUE and False
        # we are assigning the output of $testInternetConnectivity to the $bit Variable
        $bit =     $testInternetConnectivity
        
        #if the $bit is false then 
        if ( $testInternetConnectivity -ne $true) 
            {
            # show notifications
            Write-Host 'Please check your connection, I am not able to Ping www.google.com.'
            # just adding a new blank line
            "`n" 





#sleeping for 10 Seconds

Start-Sleep 10
} #end of IF


}
# end of while
# if the $bit is $true , then we are good to go.
if ( $bit -eq $true )
{
# notifications
"`n"
Write-Host 'Internet is Pingable, we are good to go.' -ForegroundColor 'Green'

}
#end of IF

# end of the script




You can also download the script code from this link :

Download Link : http://gallery.technet.microsoft.com/scriptcenter/Keep-Testing-Internet-f5c29243

Screenshots

I run the script and it found the “google.com” and give us an notification that Internet is Pingable.

29-07-2013 14-50-40

I have disconnected my laptop from internet and run the script, you can check it is continuously running.

29-07-2013 14-51-01

The internet is still disconnected and i run the script and it is showing that Internet connection is not there and in the middle I plugged in the LAN and you can see it found that google.com is working and  script is stopped.

29-07-2013 14-53-07



What i want to accomplished?

My “Main” script run when users login to the laptop. This script copy a .xls file everyday to a server before user start working on a laptop.

The problem was, sometime user not plugged in the LAN cable and sometime they are not connected to WIFI. so most of the time script fails.

So , i want to write a code , by which this script always run until it found a backup server.

To accomplish it i wrote above script code.

Description

I am setting $bit variable to False first.

$bit = $false

Now I am running the lope that, util $bit is equal to false, keep try to ping google.com



while ( $bit -eq $false ) {

              Write-Host 'Checking Internet Connection.' -ForegroundColor 'Yellow'Now I am testing the connection with www.google.com and storing the result in to variable

$testInternetConnectivity = Test-Connection -Count 3 "www.google.com" –Quiet

Now , I am updating the $bit varable with the value in $testInternetConnectivity

$bit =        $testInternetConnectivity        

if ( $testInternetConnectivity -ne $true)

{

Write-Host 'Please check your connection, I am not able to Ping www.google.com.'

                     }

}



When $bit variable became to true the below script code will run.



if ( $bit -eq $true ) {


"`n”          

Write-Host 'Internet is Pingable, we are good to go.'  -ForegroundColor 'Green }



---------------------------------------

The only confusing bit in the script code is , how are storing the Test-Connection to “google.com” and true or false.

and the trick is when we use –Quiet parameter with Test-Connection cmdlet it give the output in true and false.

Please see the below screenshots are everything will be clear.

In below screenshot, i am storing the output of Test-Connection in to variable , without –Quiet parameter and it is give me full details of Source,Destination, IP address rather then giving me result in True or false.

29-07-2013 14-56-36

Now, i added the –Quiet Parameter and you can see the result is shown is True now.

29-07-2013 14-56-59

Same here.

29-07-2013 14-57-50

29-07-2013 15-05-41

Download Link : http://gallery.technet.microsoft.com/scriptcenter/Keep-Testing-Internet-f5c29243

I hope that this trick will help you.

Thanks

Aman Dhally




clip_image001 clip_image002 clip_image003 clip_image005clip_image007







6 comments:

  1. Simple and good one :-) thanks for sharing.

    ReplyDelete
    Replies
    1. You are welcome :)

      Regards
      Aman

      Delete
  2. The technique of periodically query a status in a loop is called polling and should be avoided in general.
    A naive constructed polling loop can drive the processor usage (CPU) at 100%. The CPU is then employed only with the processing of the loop and cannot execute other programs or tasks.
    It is also a unnecessary waste of power consumption and heats the CPU (We are all greenies and the CPU does not sends the smoke of dead)

    To avoid this you should always install the Cmdlet Start-Sleep in a polling loop. This sets the PowerShell process "sleep" and gives the CPU time to do other tasks.

    Alternatively, you should always use event-driven techniques that consume practically very few system resources.
    A program can simply do nothing as long as, until a certain event has occurred.
    The program has subscribed to an event.

    Events are not as easy to use in PowerShell because PowerShell can always do only one thing, "concurrently".
    PowerShell operates all the tasks in serially order and only from a process with a single storyline (single threaded). (Like a road with only one lane and ban on passing)
    But for events you usually need two parallel courses of action (multithreading). (A road, like a highway, with multiple parallel lanes)

    So you should always change your code (refactoring) that polling can be avoided.

    Peter Kriegel
    Http://www.admin-source.de

    ReplyDelete
    Replies
    1. Hi Peter,

      Welcome.

      Thanks a lot for sharing your valuable input with me.

      I just realized that rather then keep it running constantly the pausing for a n number of seconds using {start-sleep) is a good idea.

      Powershell evening can be used, but that is a little bit tricky,.

      Regards
      Aman Dhally

      Delete
  3. I have forgot to mention. If the event who you are waiting for never occours you have an endless loop. To prevent such endless loop, it is best practice to implement a time out mechanism. So install a loop counter or a time calculation in the loop which is breaking the loop.

    Peter Kriegel
    HTTP://www.admin-source.de

    ReplyDelete
    Replies
    1. Hi Peter,

      Thanks for Sharing your valuable suggestions.

      Yes, you are right , there should be timeout mechanism should be there too.

      In my environment,user has to done this and i wont mind keep running it , until it accomplish it task.

      But in general it should be timeout after X number of minutes..

      Thanks for the advise,, will add the code .

      Regards
      Aman Dhally

      Delete