Thursday, October 16, 2014

#29 : Creating array in Powershell

Array is programming construct of most of the high level languages. It is meant to describe a collection of elements (values or variables), each selected by one or more indices that can be computed at run time by the program.

Declaring array is very simple in Powershell and there are multiple ways to achieve it :

1. Static Array

Array : Definition  
An array type is a data type that is meant to describe a collection of elements (values or variables), each selected by one or more indices that can be computed at run time by the program. Such a collection is usually called an array.
Array can be useful in your programming where you have to work on a collection of

Creating an Array in Powershell:

  1. $x=@()   
  2. $x += "Som"   
  3. $x += "Jack"   
  4. $x += "John"   
  5. $x += "Micky"   

Displaying and accessing elements of Array:
You can access each element of array with [<index_number>]. Square brackets enclosed in index number.
  1. $x[0]  
  2. $x 
Output:
Som
Som
jack
John
Mickey 


Searching an element of Array:
Array plays important role in searching in Powershell. Let's see how?

Suppose we have to search if jack exists in any of index of the array, we can search it using below statement -
    1. $x -contains "jack"    
    2. $x -contains "xx"   
    Output:
    True
    False 
     So, you may use it in your scripts like this -
    1. if ( $x -contains "jack" )   
    2. {   
    3.     Write-Host "jack exits!"   
    4. }   
    5. else   
    6. {   
    7.     Write-Host "jack does not exits!!"   
    8. }   


    Deleting an Element from Array:

    There is no direct method which can be used to delete specific index from array. But below can be tried to search and delete specific value from an Array -
    1. clear   
    2. $x=@()   
    3. $x += "Som"   
    4. $x += "Som"   
    5. $x += "Som"   
    6. $x += "Ravi"   
    7. $x += "jack"   
    8.   
    9. Write-Host "Before Deleting element named 'jack' - "    
    10. $x   
    11.   
    12. $x = $x | where {$_ -ne "jack" }   
    13.   
    14. Write-Host "After Deleting element named 'jack' - "    
    15. $x  



    Array is one of the basics of any Programming language. There are numerous other ways to create Array in Powershell.



    cls




    #--Static Array --#
     

     

    $x1 = (1,2,3)




    $x1
     
     

     
    #-OR- Write like below --#
     
     

    $x = 1 ,2 ,3


     
     
    echo "#--Just writing $x shows all elements --# "



    $x
     
     

    echo "#--Onliner to print all elements of array --# "
    $x | foreach { echo "Element - $($_)"}



     
     
    echo "#--Display all elements using foreach --# "
    foreach ( $i in $x )



    {
     
    echo "Element - $i"



    }
     
    echo "#--Display all elements using for loop --# "

    for ($c=0; $c -lt $x.Count; $c++)



    {
     
    echo "Element[$c]- $($x[$c])"



    }
     
    $y = 1 , "Som" , "Testing" , 3



    $y
     
     



     
     
    echo "#--Add two arrays --# "
    $z = $x + $y

    $z



     
     
    echo "#--Substract elements of one array --# "




    #--Below does $y -$x --#
     
     
    $n= $y | where { $x -notcontains $_ }
    $n



     
     
    echo "#--Range --#"

    $m = 1 ..6
    $m



     
     
    echo "--Adding elements to array--#"

    $Arr = @()
    $Arr += "Check-1"
    $Arr += "Check-2"
    $Arr += "Check-3"
    $Arr += "Check-4"

    $Arr



     
     
    echo "--Create Multi-dimensional Array 4x4--#"

    [string[][]]$md = @( (0,0,0,0) , (0,0,0,0), (0,0,0,0), (0,0,0,0) )

    $md[0][0]="A"
    $md[0][1]="B"
    $md[0][2]="C"
    $md[0][3]="D"

    $md[0]

    echo "------------"

    $md[1][0]="E"
    $md[1][1]="F"
    $md[1][2]="G"
    $md[1][3]="H"

    $md[1]

    echo "------------"

    $md[2][0]="I"
    $md[2][1]="J"
    $md[2][2]="K"
    $md[2][3]="L"

    $md[2]

    echo "------------"

    $md[3][0]="M"
    $md[3][1]="N"
    $md[3][2]="O"
    $md[3][3]="P"

    $md[3]




    #--Formatted display of 4x4 multi-dimensional Array--#
     
     
    echo " "
    echo "+---+---+---+---+---+"
    echo "| | 0 | 1 | 2 | 3 |"
    echo "+---+---+---+---+---+"

    for ( $a=0; $a -lt 4 ; $a++)



    {
     
    echo "| $a | $($md[$a][0]) | $($md[$a][1]) | $($md[$a][2]) | $($md[$a][3]) | $($md[$a][4]) "
    echo "+---+---+---+---+---+"


    }

     

     

     
     
    $f=@(,@(,@(,@())))

    $f[0][0][0]=1
    $f[0][0][0]=1
    $f



     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     


      

    Thursday, October 9, 2014

    #28 : Display Messagebox with Powershell

    Sometimes we need to display a messagebox to user. Especially when user interaction is required and we want to warn user or inform that a process has completed or so. Powershell leverages all .NET features available to any .NET language such as C# or VB.NET. This gives a lot of freedom to developers and there are not console world and GUI world when you are programming with Powershell. Let's take a look how we can do it.

    Below video is the complete demonstation:



    Generating a Messagebox -

    1. Load the Assembly

    [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")

    Output-

    GAC Version Location
    --- ------- --------
    True v2.0.50727 C:\Windows\assembly\GAC_MSIL\System.Windows.Forms\2.0.0.0__b77a5c561934e089\System.Windows.Forms.dll

    Note: If you don't want the output, you can simple redirect to Out-nul. This will skip displaying assembly loading statement.
    You can also cast is with [void] such as below:
    [void][System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")


    2. Display a simple Messagebox
    [System.Windows.Forms.MessageBox]::Show("We are proceeding with next step.")

    Now, the messagebox appears something like this -



    If you see above message, you will find Title is missing. Let's add a title also by adding below piece of code -
    [System.Windows.Forms.MessageBox]::Show("We are proceeding with next step." , "Status")



    So, this was all about showing message with title. This was just OK message so, there is nothing to decide for user except pressing OK button.
    Types of Messageboxes :
    We have 6 types of Messageboxes in Powershell -

    0: OK
    1: OK Cancel
    2: Abort Retry Ignore
    3: Yes No Cancel
    4: Yes No
    5: Retry Cancel

    Note: The number mentioned in left is the third parameter of Messagebox.

    If you want to show Yes No, just add 4 as third parameter -

    [System.Windows.Forms.MessageBox]::Show("We are proceeding with next step." , "Status" , 4)
    Now, this will display a Messagebox like this -



    How to get values from Messagebox?
    As you know, when you press any button, you need to get the result and work upon the decision -
    $OUTPUT= [System.Windows.Forms.MessageBox]::Show("We are proceeding with next step." , "Status" , 4)
    if ($OUTPUT -eq "YES" )
    {
    ..do something

    }
    else
    {
    ..do something else
    }

    The value of button pressed is stored in $OUTPUT variable. This variable can then be used for your programming logic.

    I have given just a primer how to use Messagebox class. But, if you want to go indepth of System.Windows.Forms.MessageBox class, you may look for the link below -

    http://msdn.microsoft.com/en-us/library/system.windows.forms.messageboxbuttons.aspx



    Wednesday, September 24, 2014

    #27 : Changing Powershell Prompt

    When you open Powershell, you get a prompt like - PS C:\Users\Administrator>. The prompt is very good, but after few days of working you feel to have a change. But the good old command 'prompt' does not work in Powershell.

    For those who don't know how to change prompt in Command Prompt, you can try below command Prompt -
    prompt $$
    -or-
    prompt $p$g

    The same command does not work in Powershell. I tried it very early days and skipped when it did not work. So, the question is - How to change Prompt in Powershell ?

    You need to create function named prompt to change the prompt easily. Follow the below steps -
    1. Open Command-Prompt of Powershell.
    2. Run the below -
    function prompt { "Posh >" ; return " " }

    The above command you need to run every time you run Powershell. So, this will be a cumbersome approach. So, let's try another approach - Change your profile which is a Powershell script that runs every time.
    1. Find the location of $profile using below command -
    echo $profile
    2. You might get a path like -
    C:\Users\Administrator\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
    3. This path does not exists usually. You can goto location Documents and create a folder named WindwosPowershell and file mentioned above. Create it and move to next step.
    4. Run the command -
    notepad $profile
    5. Copy and paste below script in the notepad and save it -


    1. function prompt
    2. {
    3. ${GLOBAL:CNT_OF_PRMT}++
    4. Write-Host ( "Posh (" + $("000000000${GLOBAL:CNT_OF_PRMT} > ").tostring().substring($("000000000${GLOBAL:CNT_OF_PRMT}").length-4 , 4) + ") > ") -foregroundcolor white -nonewline
    5. return " "
    6. }
    You might see a command prompt with a line number -
    Posh (0064) >
    Posh (0065) >

    Every time we press enter a value is increased. You can change the foregroundcolor of your choice.
    Isn't this glamorous! I like it!

    Wednesday, September 10, 2014

    #26 : How to send SMTP Mail with Powershell ?

    Many of your scripts require to send mail. There are several ways to send mail, but I am introducing you with SMTP mail sending script here. The code will accept below values which either you can hard-code inside the script or you can make a config file or ini file to get the settings. Below is simple piece of code for the same:



    How to send mail to multiple recipients?

    This can be done by modifying NOTIFY_ID variable with below -

    $NOTIFY_ID=som@foo.com,john@foo.com


    Make sure you are using a comma(,) to separate two Mail-Ids.

    How to Send HTML Formatted mail using Powershell ?

    This is another good option which can be done easily with Powershell. You need to just add one more line inside the code:



    Easy and Simple. Enjoy Scripting!!

    Thursday, September 4, 2014

    #25 : Create a ShortCut with Powershell

    Creating a Shortcut might be a difficult task in any scripting language in Windows. Not sure how difficult or simple is there in Unix.

    Let's take a look on the simple few lines which accomplish this task -

    clear
    $wsc = New-Object -ComObject ("Wscript.Shell")$sc=Join-Path -Path "d:\test" -childpath "Notepad.lnk"
    $slink=$wsc.CreateShortcut($sc)$slink.TargetPath = "C:\windows\notepad.exe"
    $slink.WindowStyle = 0
    $slink.Hotkey = "CTRL+SHIFT+F"
    $slink.IconLocation = "notepad.exe, 0"
    $slink.WorkingDirectory = "d:\Test"
    $slink.Save() 
    
    

    Since this uses Wscript.Shell which is VBScript shell, there are some Windows version where you do not see desired output. Please let me know..

    Enjoy!

    #112: How to handle xml document in Powershell?

     In PowerShell, you can handle XML data using various cmdlets and methods provided by the .NET Framework. Here's a basic guide on how to...