Lessons in PowerShell - Conditions and Operators

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.

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

Switch

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.

Example:

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

Output:

1Multi-match Exact word1
2Multi-match Exact word2
3Pattern match Exact word2
4Multi-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

Note:

  • 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"
aTESTd
-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
$a = { Get-Process | Select -First 2 }
&$a

Boolean Expressions

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

TRUE 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

Lessons in PowerShell - Escape Sequences

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

Escape Sequences

The escape character in Windows PowerShell is the backwards apostrophe.

Escape Sequence Description
`0 (null)
`a (alert)
`b (backspace)
`f (form feed)
`n (new line)
`r (carriage return)
`t (tab)
`v (vertical quote)

Lessons in PowerShell - Exception Handling

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

Throw

The keyword “Throw” allows an exception to be thrown. The argument for the Throw keyword can be a string, exception or ErrorRecord.

1throw "Some description about the exception"

Traps

A trap is a mechanism to catch an exception, although it behave more like the Visual Basic 6 On Error functionality. The continue keyword will continue execution at the script statement after the one that caused the trap. $? is updated but no error record is generated. The break keyword will rethrow the exception.

 1Trap [ExceptionType] 
 2{
 3    if (...) 
 4    { 
 5        continue
 6    } else (...)
 7    { 
 8        break
 9    }
10
11    # Doing nothing will do what is specified in the $ErrorActionPreference setting
12}

Try / Catch / Finally

There is no native support in PowerShell Version 1 for the typical Try / Catch / Finally syntax found in other languages. However with the use of the & invoke operator, the Try / Catch / Finally syntax can be mimicked.

 1&{
 2     &{   # Try
 3          # Do your processing here
 4     } 
 5     trap # Catch
 6     {
 7         Write-Host "TRAPPED: " + $_.Exception.GetType().FullName
 8         Write-Host "TRAPPED: " + $_.Exception.Message
 9         continue   # So that the "Finally" stuff gets executed
10     }
11} #Finally
12# Put your finally code here

However, from PowerShell Version 2, you can use the familiar try / catch syntax.

1    try {
2        ...
3    } catch {
4        ...
5    }

Lessons in PowerShell - Functions

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

Functions

1function MyFunction 
2{
3    write-object $args[0]
4}
5
6function test ([string] $label="default label", [int] $start=0)
7{ 
8    ...
9}

Lessons in PowerShell - Logging From A Script Running Via Windows Task Scheduler

Logging and tracing information can normally be written to the host console, standard output or standard error streams. However, when a PowerShell script is run from the Windows Task Scheduler, those mechanisms are typically not available.

To work around this situation, I decided to create a log file for my PowerShell Script which is executed from Windows Task Scheduler.

For a start, we can use the .NET StreamWriter class to create a file stream.

1$logFile = New-Object System.IO.StreamWriter("C:\temp\Script.log")

Please note: you must ensure that the user account the script runs under needs to have file system security access to that specific folder and file.

We can then create a function that will write a message to the log file and also flush the stream (I wanted to closely monitor the progress of the script while it may be running, so I am explicitly flushing the stream).

1Function LogMessage($message)
2{
3    $logFile.WriteLine($message)
4
5    $logFile.Flush()
6}

And using the mimicked PowerShell Version 1 Try / Catch / Finally script block, we can ensure that even if an error occurs, the stream will be closed. See the bottom line below.

Here is the script in its entirety.

 1# Trap settings
 2$ReportErrorShowExceptionClass=$true
 3$ReportErrorShowInnerException=$true
 4$ReportErrorShowSource=$true
 5$ReportErrorShowStackTrace=$true
 6
 7# Setup log file functionality
 8$now=Get-Date
 9$logFile = New-Object System.IO.StreamWriter("C:\temp\Script.log")
10
11Function LogMessage($message)
12{
13    $logFile.WriteLine($message)
14    $logFile.Flush()
15}
16
17&{
18    &{ #Try 
19          LogMessage("Started at " + $now)
20          ...
21          LogMessage("Successfully finished")
22    } 
23    trap #Catch
24    {
25        LogMessage("TRAPPED: " + $_.Exception.GetType().FullName) 
26        LogMessage("TRAPPED: " + $_.Exception.Message)
27        continue # So that the "Finally" gets executed
28    }
29} #Finally
30$logFile.Close()

There we have it… a PowerShell script that runs under Windows Task Scheduler and writes out to a log file.

Of course, using the PowerShell Version 2 Try/Catch statement is much nicer than this PowerShell Version 1 equivalent.

Lessons in PowerShell - Looping Through File Folders

One way in PowerShell to get a collection of file folders is by using the .NET System.IO.Directory.GetDirectories function. Time is short, and I am familiar with that, so I will use the .NET library in this example script.

Here is one way in which it can be done.

1$folders=[System.IO.Directory]::GetDirectories("c:\xxxx")
2
3foreach ($folderName in $folders)
4{                
5    ...
6}

If we wanted to, within the loop we could instantiate a System.IO.DirectoryInfo object to give us more information about the folder.

1$folder = New-Object System.IO.DirectoryInfo($folderName)                    

And then we can access the properties on that class, like the folder’s LastWriteTime in order to find out how old it is.

Here is a complete script.

 1$now = Get-Date
 2$yesterday = $now.AddDays(-1)
 3$folders=[System.IO.Directory]::GetDirectories("c:\program files")                    
 4
 5foreach ($folderName in $folders)                    
 6{
 7    $folder = New-Object System.IO.DirectoryInfo($folderName)
 8
 9    if ($folder.LastWriteTime -lt $yesterday)                    
10    {                     
11        Write-Host("Folder " + $folderName + " is at least a day old")                    
12    }
13    else
14    {
15        Write-Host("Folder " + $folderName + " is less than a day old")
16    }                    
17}

Lessons in PowerShell - Loops

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

For

Format:

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

Example:

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

For Each

Format:

1[:label]
2
3foreach (identifier in collection) {}
4
5Expression | foreach {}
6
7Expression | foreach {BEGIN{} PROCESS{} END{}}

Examples:

1$i = 1,2,3
2foreach ($z in $i) { Write-Object $z } 
3
4Get-Process | foreach {
5    BEGIN{$x=1}
6    PROCESS{$X++} 
7    END{"$X Processes"}
8}

Do Until

1do
2{ 
3    ...
4} until (condition)

While

1[:label] while (condition)
2{
3    ...
4}

Do While

1do
2{ 
3    ...
4} while (condition)

Lessons in PowerShell - Running a PowerShell Script Via Windows Task Scheduler

In order to run a Windows PowerShell script through the Windows Task Scheduler:

  • Run the Task Scheduler:

    Start ➞ Control Panel ➞ Administrative Tools ➞ Task Scheduler

  • Create and schedule a task that starts a program.

    Specify the program to run as:

    1C:\WINDOWS\system32\WindowsPowerShell\v1.0\Powershell.exe
    

    Specify the arguments as:

    1C:\PathToMyScript\MyScript.ps1
    

The PowerShell script will now run as scheduled.

Lessons in PowerShell - Documentation

When you install PowerShell, documentation is also installed. This documentation can be found under the following folder:

Start Menu ➞ All Programs ➞ Windows PowerShell 1.0 ➞ Documents ➞ en-US

The Windows PowerShell Getting Started Guide (GettingStarted.rtf) is a 32-page introduction to using the shell and the Windows PowerShell scripting language.

The Windows PowerShell Primer (UserGuide.rtf) is a companion document to the Getting Started Guide. It describes the features of Windows PowerShell and the Windows PowerShell scripting language with examples of how to use the new shell.

The Windows PowerShell Language Quick Reference (QuadFold.rtf) is a one-page foldable guide to the Windows PowerShell scripting language.