powershellscripts.com

Tutorials  Tutorials

Powershell Basics
Introduction to Windows PowerShell Part 1
Introduction to Windows PowerShell Part 2
Introduction to Windows PowerShell Part 3
PowerShell Script Signing
PowerShell Scheduled Tasks
PowerShell Networking Tasks

Powershell Advanced Tutorials
PowerShell and VMware Introduction



 



Introducing PowerShell Part 2: Syntax and Programming Constructs

In part one of this series we took a quick look at some of the basic commands and features available within PowerShell.  In part 2 we are going to try to cover basic syntax (i.e. what is the escape character?), and also look at the different selection (if... then) and iteration (while, for, etc..) constructs available to the PowerShell programmer.

Variables
In PowerShell a variable is created by using the $ character. Because PowerShell is a type-promiscuous language specifying the variable type (string, int etc..) is not required.  You can however specify type by proceeding the variable with a bracketed value:
	[int]$a = 10	
A Partial Listing of PowerShell Automatic Variables
$$ Last token of the previous command line
$? Boolean status of last command
$^ First token of the previous command line
$_ Current pipeline object
$Args Arguments to a script or function
$Error Array of errors from previous commands
$Foreach Reference to the enumerator in a foreach loop
$Home The user’s home directory; usually set to %HOMEDRIVE%\%HOMEPATH%
$Host Reference to the application hosting the POWERSHELL language
$Input Enumerator of objects piped to a script
$LastExitCode Exit code of last program or script
$Matches Hash table of matches found with the –match operator
$PSHome The installation location of Windows PowerShell
$profile The standard profile (may not be present)
$StackTrace Last exception caught by Windows PowerShell
$Switch Enumerator in a switch statement


Variable Scope
Variables in PowerShell can belong to 4 different scope level's Global, Local, Private or Script.  All variables that we have used up to this point have been global.  Scope can become more important when writing more complicated logic involving multiple functions, calling external scripts, etc...  To display all current variables and their scope use the following command
	PS C:\Documents and Settings\D> Get-Variable -scope global

	Name Value
	---- -----
	Error {MissingArgument,Microsoft.Powe...
	DebugPreference SilentlyContinue...
	PROFILE C:\Documents and Settings\D\My... 
	...
Concatenation
To concatenate variables holding strings simply use the + sign.  Be careful though, PowerShell will return the sum of two integers using the + sign.  If you need to concatenate multiple number variables you must first type cast them as strings.
	PS c:\scripts\> $a=1
	PS c:\scripts\> $b=2
	PS c:\scripts\> $c=$a+$b
	PS c:\scripts\> $c
	3
	PS c:\scripts\> [string]$a="1"
	PS c:\scripts\> $c=$a+$b
	PS c:\scripts\> $c
	12
Strings and Quotes
A string in PowerShell is typically defined by matching double or single quote "I am a string".  When using double quotes you may escape special characters (such as a double quote) by either repeating the character or using a backtick.  Double quotes are however ignored when using single quotes.  Let's look at some examples.
	PS C:\scripts> $string = "I am a string!"
	PS C:\scripts> $string
	I am a string!
	PS C:\scripts> $string = 'I am a string!'
	PS C:\scripts> $string
	I am a string!
	PS C:\scripts> $string = "I "am" a string!"
	Unexpected token 'am a string!' in expression or statement.
	At line:1 char:28
	+ $string = "I "am" a string!" <<<<
	PS C:\scripts> $string = "I `"am`" a string!"
	PS C:\scripts> $string
	I "am" a string!
	PS C:\scripts> $string = 'I "am" a string!'
	PS C:\scripts> $string
	I "am" a string!
Likewise strings containing variables should be double quoted
	PS C:\scripts> "What are you? $string"
	What are you? I "am" a string!
Operators
For whatever reason PowerShell does not support >, >=, etc.... Here are the list of supported comparison operators:

-lt -- Less than
-le -- Less than or equal to
-gt -- Greater than
-ge -- Greater than or equal to
-eq -- Equal to
-ne -- Not equal to
-like – Like; uses wildcards for pattern matching

Array Collections
Arrays in PowerShell can be created by using the comma operator, and accessed with the typical [] notation.  PowerShell arrays are zero based, that is to say the first element is [0].  Let's look at some array creation, access, and expansion examples.
	PS C:\scripts> $myarray = ("a","b","c",1,2,3)
	PS C:\scripts> $myarray
	a
	b
	c
	1
	2
	3
	PS C:\scripts> $myarray[2]
	c
	PS C:\scripts> $myarray[2] = 10
	PS C:\scripts> $myarray[2]
	10
	PS C:\scripts> $myarray
	a
	b
	10
	1
	2
	3
	PS C:\scripts> $myarray.length
	6
	PS C:\scripts> $myarray += ,"newone"
	PS C:\scripts> $myarray.length
	7
Hashtables
Also know as associative arrays, hastables map keys to values.  To define a hashtable use the @ token and enclose the key pairs in {}.  Let's try some examples.
	PS C:\scripts> $myhash =@{ Ford = "Mustang"; Dodge = "Charger"; Chevy = "Camero" }
	PS C:\scripts> $myhash
	
	Name Value
	---- -----
	Dodge Charger
	Ford Mustang
	Chevy Camero
Accessing the data can be done with both property and array notation, which is nice.
	PS C:\scripts> $myhash["Chevy"]
	Camero
	PS C:\scripts> $myhash.Chevy
	Camero
	PS C:\scripts> $myhash.keys
	Dodge
	Ford
	Chevy
	PS C:\scripts> $myhash.remove("Dodge")
	PS C:\scripts> $myhash
	
	Name                           Value
	----                           -----
	Ford                           Mustang
	Chevy                          Camero
Selection
PowerShell supports all the usual constructs, if/then, if/then/else, if/then/elseif/else, and switch.  The example below uses the backtick for line wrapping.
	PS C:\scripts> $x=0; if ($x = 0) {"looks like x equals 0"} `
	>> else {"looks like x equals 1"}
	>>
	looks like x equals 1
And here is a switch statement:
	PS C:\scripts> switch ("abc") { "abc" {"abc matches"} "def" {"def does not"}}
	abc matches
Iteration
PowerShell supports while, do-while, for, and foreach loops.  The standard break and continue statements are also supported.
	PS C:\scripts> $x=0
	PS C:\scripts> while($x -le 3)`
	>> {"x is still less than or equal to 3";$x++}
	>>
	x is still less than or equal to 3
	x is still less than or equal to 3
	x is still less than or equal to 3
	x is still less than or equal to 3
	
	PS C:\scripts> do {$x;$x++} while ($x -le 3)
	1
	2
	3
	
	PS C:\scripts> for ($i=0; $i -lt 3; $i++) {$i}
	0
	1
	2