Variable

Set variable value in two ways:

1.  Use dollar sign ($) before the variable name. E. g. $a=12

2. Use cmdlet set-variable,  when you specify the -name argument, you do not use the dollar sign.

set-variable -name a -value 12

Constants are created by using the Set-Variable cmdlet and specifying the -option argument to be equal to constant.

To make the $b variable can only contain an integer:

[int]$b=5

For other type of variables:

Type Use of Constants
[int] A 32-bit signed integer
[long] A 64-bit signed integer
[string] A  xed-length string of Unicode characters
[char] A Unicode 16-bit character, UTF-16
[bool]  a True or false value
[byte] An 8-bit unsigned integer
[double] A double-precision 64-bit floating-point number
[decimal] An 128-bit decimal value
[single] A single-precision 32-bit  floating-point number
[array] An array of values
[xml] An XML document
[hashtable] A hashtable object (similar to a dictionary object)

 

 

To read the logon server, homepath, appdata path, and home drive from registry, we can use the following script:

 

# ReadUserInfoFromReg.ps1

$strUserPath = "\Software\Microsoft\Windows\CurrentVersion\" `

               + "Explorer"

$strUserName = "Logon User Name"

$strPath = "\Volatile Environment"

$strName = "LOGONSERVER","HOMEPATH", "APPDATA","HOMEDRIVE"

Set-Location HKCU:\

Get-ItemProperty -path $strUserPath -name $strUserName |

Format-List $strUserName foreach ($i in $strName)

{Get-ItemProperty -path $strPath -name $i | Format-List $i}

By default, when working with Windows PowerShell, you do not need to declare variables before use. When you use a variable to hold data, it is declared. All variable names must be preceded with a dollar sign ($) when they are referenced. There are a number of special variables in Windows PowerShell. These variables are created automatically and have a special meaning.

Name Use
 $^ This contains the frst token of the last line input into the shell.
$$ This contains the last token of the last line input into the shell.
$_ This is the current pipeline object; it’s used in script blocks, flters, Where-Object,
ForEach-Object, and Switch.
$? This contains the success/fail status of the last statement.
$Args This is used with functions or scripts requiring parameters that do not have a param
block.
$Error This saves the error object in the $error variable if an error occurs.
$ExecutionContext This contains the execution objects available to cmdlets.
$foreach This refers to the enumerator in a foreach loop.
$HOME This is the user‘s home directory (set to %HOMEDRIVE%\%HOMEPATH%).
$Input This is input that is piped to a function or code block.
$Match This is a hash table consisting of items found by the -match operator.
$MyInvocation This contains information about the currently executing script or command line.
$PSHome This is the directory where PowerShell is installed.
$Host This contains information about the currently executing host.
$LastExitCode This contains the exit code of the last native application to run.
$true This is used for Boolean TRUE.
$false This is used for Boolean FALSE.
$null This represents a null object.
$this In the Types.ps1xml fle and some script block instances, this represents the current
object.
$OFS This is the output feld separator used when converting an array to a string.
$ShellID This is the identifer for the shell; this value is used by the shell to determine the ex
ecution policy and what profles are run at startup.
$StackTrace This contains detailed stack trace information about the last error.

String

There are two kinds of strings: literal strings and expanding strings.

  • Expanding string, signified when you use the double quotation mark, ” .In an expanding string, the value that is contained in a variable is displayed to the screen when a line is evaluated. You can use the escape character to force display the name of the variable.
    $i=12
    “$i equals”+$i
    >>12 equals 12
    “`$i equals”+ $i
    >>$i equals 12
  • The literal string uses the single quotation mark, ‘.  And the literal string still display the name of the variable, does not display the value.
    $i=12
    ‘$i equals’+$i
    >>$i equals 12
Automatic incremental

In a loop such as while, use i++ syntax to increment the value of i, preventing the infinite loop.

While

In Powershell, the action to be performed is positioned inside a pair of braces. This construct read the condition first, then execute the action.

Let’s read a text file line by line in this example. The number of lines in the text  le is represented by the length property

To start a loop, you initialise a variable $i and set the value 0. To make the loop end at some point, you increment the value of the $i variable by one. To do this, you use the $i++ syntax.

Do … while: You use the Do statement and open a set of braces (curly brackets). Inside these curly brackets you have a script block.

$i = 0

$ary = 1..5

do

{

$ary[$i]

 $i++

} while ($i -lt 5)

You can copy some text to a file called testfile.txt in c:\fso.

$i = 0

$fileContents = Get-Content -path C:\fso\testfile.txt While ( $i -le $fileContents.length )

 {

  $fileContents[$i]

  $i++

}

Do until: 

In Windows PowerShell, the Do…While and Do…Until constructions always run at least once.

It runs until a condition is met.

The difference between Do…Until and Do…While

Do…While runs while a condition is true and Do…Until runs until a condition becomes true.

Array

But the  first element number in the array is always 0 in Windows PowerShell.

You can use following ways to create array:

  1. while statement.
    $i = 0
    
    While ($i -lt 5)
    
     {
    
      "`$i equals $i. This is less than  5"
    
      $i++
    
     }

     

  2. comma: To create an array, you just have to assign multiple pieces of data to the variable. To do this, you separate each piece of data by a comma.$ary = 1,2,3,4,5
  3. Range operator:  beginning and the ending number separated by two periods.
    $ary = 1..5
    Note that  Unfortunately, the range operator does not work for letters. But there is nothing to prevent you from creating a range of numbers that represent the ASCII value of each letter, and then casting it to a string later.

      $i = 0
          $caps = 65..91
          do
          {
           [char]$caps[$i]
    
           $i++
    
          } while ($i -lt 26)
Foreach statement

As long as there are more elements in the collection or array, the statements inside the loop continue to execute for each element. When there are no more elements in the collection or array, the loop is exited.

$ary = 1..5
ForEach($i in $ary)
{
 if($i -eq 3) { break }
$i }

"Statement following foreach loop"

To exit the loop early,

  • you can use if statement with the Break statement, note that it still runs the line of code following the Foreach loop.
  • Exit: If you did not want to run the line of code after the loop statement, you would use the exit statement
Continue statement

The continue returns flow to the top of the innermost loop that is controlled by a While, For, or Foreach statement.

E.g. If I want to skip the number 3, I can use the If statement to see if the $i variable holds the number 3. If it does, I can use the Continue statement to return to the top of the Foreach loop, and it will continue processing. The revised script is shown here:

[array]$a = 1..6
foreach ($i in $a)
{
 If($i -eq 3){continue}
 $i
}

The result will be:

1
2
4
5
6

 

If statement

The operators that you may use i the condition of IF statement.

Operator Description Example Result
-eq Equals $a=5; $a -eq 4 False
-ne Not equal $a=5; $a -ne 4 True
-gt Greater than  $a=5; $a -gt 4 True
-ge Greater than or equal to $a=5; $a -ge 5 Ture
-lt Less than $a=5; $a -lt 5 False
-le Less than or equal to $a-5; $a -le 5 True
-like wildcard comparison $a=”This is Text”; $a -like “Text” False
$a=”This is Text”; $a -like “*Text” True
-notlike wildcard comparison $a=”This is Text”; $a -notlike “Text” True
-match Regular expression comparison $a=”text is Text”; $a -match “Text” True
-notmatch Regular expression comparison $a=”This is Text”; $a -notmatch “Text$” False

 

Switch

Similar to Case statement in some programming language.

If you have two statement matching one value:

$a = 2

Switch ($a)
{
 1 { '$a = 1' }
 2 { '$a = 2' }
 2 { 'Second match of the $a variable' }
 3 { '$a = 3' }
 Default { 'unable to determine value of $a' }

}

"Statement after switch"

When the DemoSwitchMultiMatch.ps1 script runs, the second and third conditions will both be matched, and therefore their associated script blocks will be executed. The DemoSwitchMultiMatch.ps1 script produces the output shown here:

$a = 2

Second match of the $a variable

Statement after switch

Switch statement can handle an array in the variable $a without any modi cation. The array is shown here:

$a = 2,3,5,1,77

The complete DemoSwitchArray.ps1 script is shown here:

$a = 2,3,5,1,77

Switch ($a)

{

 1 { '$a = 1' }

 2 { '$a = 2' }

 3 { '$a = 3' }

 Default { 'unable to determine value of $a' }

}

"Statement after switch"

If you do not want the multimatch behavior of the Switch statement, you can use the Break statement to change the behavior.

The Switch statement will be exited when the  first match occurs.

Change the script block into :

 1 { '$a = 1' ; break }

 2 { '$a = 2' ; break }

 3 { '$a = 3' ; break }