Lessons In PowerShell - Loops

   Submit to Reddit      

The following useful information is primarily taken from the Windows PowerShell Language Quick Reference (QuadFold.rtf) documentation.



[:label] for ([initializer]; [condition]; [iterator]) {}


for ($i=0; $i -lt 5; $i++) { Write-Object $i }

For Each


foreach (identifier in collection) {}

Expression | foreach {}

Expression | foreach {BEGIN{} PROCESS{} END{}}


$i = 1,2,3
foreach ($z in $i) { Write-Object $z } 

Get-Process | foreach {
    END{"$X Processes"}

Do Until

} until (condition)


[:label] while (condition)

Do While

} while (condition)

Lessons In PowerShell - Conditions and Operators

   Submit to Reddit      

The following useful information is primarily taken from the Windows PowerShell Language Quick Reference (QuadFold.rtf) documentation.

If / Elseif / Else

When executed on the command line, the closing brace must be on the same line as the preceding keyword.

if (condition) {...} 
elseif (condition) {...} 
else {...}</blockquote>


The variable $_ is available in the script. $_ represents the current value being evaluated. If an array is used in switch, each element of the array is tested.


$var = "word1","word2","word3"
switch -regex ($var) {
  "word1" {"Multi-match Exact " + $_ }
  "word2" {"Multi-match Exact " + $_ }
  "w.*2" {"Pattern match Exact " + $_ }
  default {"Multi-match Default " + $_ }


Multi-match Exact word1
Multi-match Exact word2
Pattern match Exact word2
Multi-match Default word3

Comparison Operators

The following operators can be used in the condition expressions.

Operator Description Example (true)
-eq Equal 1 -eq 1
-ne Not equal 1 -ne 2
-gt -ge Greater than, greater than or equal to 2 -gt 1
1 -ge 1
-lt -le Less than, less than or equal to 1 -lt 2
1 -le 1
-like Like - for text using wildcards "abc.efg" -like "?bc.*"
-notlike Not Like "abc.efg" -notlike "b*"
-contains Contains 1,2,3 -contains 1
-notcontains Not Contains 1,2,3 -notcontains 4

Prepend "i" for a case-insensitive operation. (e.g. -ieq) Prepend "c" for a case-sensitive operation. (e.g. -ceq)

Logical Operators

The following operators can be used for logical operations.

Operator Description Example (true)
-and Logical AND (1 -eq 1) -and (1 -ne 2)
-or Logical OR (1 -eq 1) -or ($FALSE)
-not or ! Logical NOT -not ($FALSE)

Binary Operators

The following operators can be used for binary operations.

Operator Description
-band Binary AND
-bor Binary OR
-bnot Binary NOT

String Operators

The following operators can be used on strings.

Operator Description
+ Concatenate two strings
* Repeat a string some number of times
-f Format a string (.NET format specifiers)
-replace Replace operator
"abcd" -replace "bc", "TEST"
-match Regular expression match
-like Wildcard matching

Type Operators

The following operators can be used on types.

Operator Description Example (true)
-is Type evaluator $a -is [string]
-as Type converter 100 -as [string]

Command Expansion Operators

The following operators can be used for command expansion.

Operator Description
$( ) Returns null
$(1,2,3) Returns an array containing 1,2,3.
$(Get-Alias a*) Returns evaluation of the expression
@(Get-Alias;Get-Process) Executes the two commands and returns the results in an array

Other Operators

Operator Description Example (true)
, Array constructor
.. Range operator
& Invoke a script block or the name of a command or function $a = "Get-Process"
$a = { Get-Process | Select -First 2 }

Boolean Expressions

The following expressions will result in a boolean value of $TRUE or $FALSE.

Any string of length > 0 except the word "false" Empty string or the string "false"
Any number !=0 Any number = 0
Array of length > 1 Array of length 0
Array of length 1 whose element is TRUE Array of length 1 whose element is FALSE
A reference to any object Null

SOLID Principles

   Submit to Reddit      

In a previous posting on behaviour-driven programming, I quickly referenced 'Uncle Bob' Robert C. Martin's website where he outlines the SOLID Principles.

I wanted to expand upon that and provide a few more helpful links.

The best examples I have seen that demonstrates these principles can be found in a series of short videos on DimeCasts.net.

Scott Hanselman too has a number of podcasts where he is directly interviewing 'Uncle Bob': Hanselminutes Podcast 145 - SOLID Principles with Uncle Bob - Robert C. Martin

When I listened to this podcast, I was quite pleased to hear and have my personal experience validated when 'Uncle Bob' rated the Single Responsibility Principle as the most important. In my personal experience, and in the experience of a number of my colleagues, this principle alone has had the largest positive effect in the quest to write cleaner and more intuitive code.

Hanselminutes Podcast 150 - Uncle Bob Martin, this time with feeling

And a more recent podcast discussing the related topic of professionalism.

Hanselminutes Podcast 171 - The Return of Uncle Bob

Lessons In PowerShell - Variables and Declarations

   Submit to Reddit      

The following useful information is primarily taken from the Windows PowerShell Language Quick Reference (QuadFold.rtf) documentation.

Automatic Variables

PowerShell includes the following in-built 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
$True Boolean True
$False Boolean False
$Null Null

Variable Declaration

Variables and other data elements may be instantiated in different scopes:

  • Variables in the global scope are visible in all scopes.
  • Variables in the script scope are visible to all scopes within that script file.
  • Variables in the local scope are visible only in the current scope and its children.
  • Private scope variables are visible only to that current scope.

A scope is created in the body of a shell function.


$[scope:]name or ${anyname} or ${any path}


$a = 1
$global:a = 1    # Visible everywhere
$local:a = 1    # defined in this scope and visible to children
$private:a=1    # same as local but invisible to child scopes
$script:a=1    # visible to everything in this script
$env:path = "d:\windows"
${C:\TEMP\testfile.txt}="This writes to a file"
Get-Variable -scope 1 a    #Gets value from the parent scope
Get-Variable -scope 2 a    # grandparent

Type Declaration

Variables also can be declared as specific data type by prefixing the variable declaration with the data type.

[bool] or [boolean] A boolean (True or False) value
[byte] An 8-bit unsigned character
[char] A Unicode 16-bit character
[string] String of Unicode characters
[datetime] A System.DateTime object
[int] A 32-bit signed integer
[long] A 64-bit signed integer
[single] A Single-precision 32-bit floating point number
[double] Double-precision floating number
[decimal] A 128-bit decimal value
[xml] A xml object
[array] An array of values
[hashtable] A System.Collections.Hashtable object
[wmi] Windows Management Instrumentation (WMI) instance or collection
[wmiclass] WMI class
[adsi] Active Directory Services object

A variable's type also can be declared as a .NET Framework class by using the full class name. For example:

[System.Int32] $amount = 1234