Title: MSH LANGUAGE
Author: James W. Truher
Last saved by: Tim Green
Company: TruTech

PowerShell 
Quick Reference

Providers

Windows PowerShell extends the drive concept to include many data stores, not just the file system.
Provider | Drive | Description
Alias | Alias: | PowerShell aliases
Certificate | Cert: | x509 certs for digital signatures
Environment | Env: | Environment variables
FileSystem | A-Z: | File system drives
Function | Function: | PowerShell functions

Registry

HKLM:
HKCU:

Registry

Variable | Variable: | PowerShell variables
WS-Mgmnt | WSMan: | WS-Management config info.

Data Types

[int], [long] | System.Int32, .Int64
[string], [char] | .String, .Char
[bool] | .Boolean
[byte] | .Byte
[single],[float] | .Single
[double], [decimal] | .Double, .Decimal
[regex] | .Text.RegularExpressions.Regex
[array] | .Array
[hashtable] | .Collections.Hashtable
[datetime] | .DateTime
[xml] | .Xml.XmlDocument
[ref] | PSReference (i.e. Pointer)
Get Object Type: $a.GetType()

Native Support for Different Type Systems

PowerShell adapts WMI, XML, ASDI, ADO, and COM objects to provide a common syntax to access properties and methods.   
.NET Object:  New-Object  -Type <.net object> [parms]
COM Object: New-Object  -ComObject “<ProgID>”
WMI Object: Get-WmiObject  -class <wmi_class>
Examples: $d = New-Object –Type System.DateTime 2009,1,1
                   $c = New-Object –ComObject “wscript.network”
                   $w = Get-WmiObject Win32_Process

Object Properties

Object’s properties are referenced directly with the “.” operator.
$a = Get-Date
$a.Date
Static properties can be referenced with the “::” operator
[DateTime]::Now

Method Calls

Methods can be called on objects. Examples:
$a = “This is a string”
$a.ToUpper()
Static Methods are callable with the “::” operator
[DateTime]::IsLeapYear(2005)

Variables & Scope

Format:                $[scope:]name  or ${anyname} or ${any path}
Typed variable:  [int]$r = 5
Scope Examples:
$global:a  = 4   # visible in all scopes
$script:a   = 5   # visible in all scopes within script
$local:a    = 3   # visible in current scope and children
$private:a = 6  # visible in current scope only
Constants: 
set-variable –name pi –value 3.142 –option constant
$c = 2 * $pi * $r     # created w/o $, but referenced with $
Non-Obvious Examples:
${!@#$%^&*()}=3
${C:\TEMP\testfile.txt}=”This writes to a file”
Get-Variable –scope 1 a  # Gets $a from the parent scope
Get-Variable –scope 2 a  # grandparent

Numerics & Strings

Numerics:         Hex Prefix            -   ‘0x’
                           Multiplier Suffix  -   KB, MB, GB
String Constants:
“this is a string, this $variable is expanded as is $(2+2)”
‘this is a string, this $variable is not expanded’
@”
This is a “here string” – quote/variable expansion rules apply.
With @”, variables expand, with @’, they don’t.
”@
Common String Methods
$s.Length(), .Substring(), .Split(), .Insert, .Replace
$s.Trim(), .TrimStart(), .TrimEnd(), .PadLeft(), .PadRight()
$s.ToUpper(), .ToLower()
Special Escape Sequences
`0 | (null) | `r | (carriage return)
`a | (alert) | `t | (tab)
`b | (backspace) | `v | (vertical quote)
`f | (form feed) | `$ | $
`n | (new line) | `` | (backtick)

Arrays

“a”,“b”,”c” | array of strings
@() | empty array
@(2)    or     ,”hi” | array of 1 element
1,(2,3),4 | array within array
$a[5]           $a[-1] | get 6th element, get last element
$a[2][3] | multi-dimensional array access
$a[2..20] | Return elements 3 thru 21
$a.length  or  $a.count | Number of elements
$a.rank | Number of dimensions
$a.SetValue(‘XYZ’,0) | Updates the first value in array

$a = [Array]::CreateInstance([int],2,2)
$a = new-object "Object[,]" 2,2

Init empty array of int or objects

Associative Arrays (Hashtables)

$hash = @{ } | Create empty hashtable
$h =@{foo=1;bar=2} | Create and init a hashtable
$hash.key1 = 1 | Assign 1 to key “key1”
$hash.key1 or  $hash["key1"] | Returns value of key1
$hash.keys | Returns all hash keys
$hash.ContainsKey(‘key1’) | Returns true if key exists

Operator Precedence
In Windows PowerShell, operators are evaluated in the following precedence:  () {}, @ $, !, [ ], ., &, ++ --, Unary + -, * / %, Binary + -, Comparison Operators, -and –or, |, > >>, =
Arithmetic Operators

+ | addition, concatenation | % | Modulus
- | Subtraction | ++ | Unary increment
/ | Division | -- | Unary decrement
* | multiplication, string repetition

Assignment Operators
=, +=, -=, *=, /=, %=
Logical Operators
!, -not, -and, -or, -xor
Comparison Operators

-eq, -ne | Equal, Not Equal
-gt –ge | Greater than, greater than or equal to
-lt –le | Less than, less than or equal to
-iOp, -cOp | Prepend i or c to indicate case-sensitivity

String Operators

+ | Concatenate two strings
* | Repeat a string some number of times
-f | Format a string (.NET format specifiers)

-replace

"abcd" –replace “bc”, “TEST”
Output: aTESTd

-[not]match | Regular expression match
-[not]like | Wildcard matching
-join, -split | (v2) Join and split strings

Array Operators

1,2,3,5,3,2 –contains 3 | Does array have a 3 in it
1,2,3,5,3,2 –eq 3 | Return all elements equal to 3
1,2,3,5,3,2 –lt 3 | Return all elements less than 3
Other operators | -gt, -le, -ge, -ne, -notcontains

Command Expansion Operators

$(Get-Alias a*) | Returns evaluation of the expression
@(Get-Alias;Get-Process) | Executes the two commands and returns the results in an array

Call/Invoke Operator

& command [parms]       
Invokes a script block, command, function or executable.  
Example: $a = { Get-Process }    or      $a = (explorer.exe)
& $a       # note space between & and command

Other Operators

, | Array constructor | -band | Binary and
.. | Range operator | -bor | Binary or
-is[not] | Type evaluator | -bnot | Binary not
-as | Type convertor | -bxor | Binary exclusive or

Boolean Values and Operators

TRUE | FALSE
$true | $false
Any string of length > 0 | Empty string
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

Formatting & Output

Format-Table | Formats a set of properties into a table.
Format-List | Displays properties 1 per line.
Format-Wide | Displays a  property in multiple cols.
Format-Custom | Complex formatting
Out-Null | Deletes output.
Out-Default | Output goes to the default formatter and to the default output cmdlet.
Out-Host | Output goes to the terminal.
Out-File | Output to a file.
Out-Printer | Output to a printer.
Out-String | Output s objects as a series of strings.
Out-GridView | (v2) Outputs to an interactive table in a separate window.
Write-Host | Writes customized output to a host.
Write-Progress | Displays a progress bar within a Windows PowerShell command window.
Write-Debug | Writes a debug message to the console.
Write-Verbose | Writes text to verbose message stream.
Write-Warning | Writes a warning message.
Write-Error | Writes an object to the error stream as non-terminating exception.
Write-Output | Sends the specified objects to the next command in the pipeline.
Write-EventLog | Writes an event to an event log.

System Variables (partial list)

$^, $$ | First, last token of the previous command line
$? | Boolean status of last command
$_ | Current pipeline object
$Args | Array of arguments to a script or function
$Error | Array of errors from previous commands
$Foreach | The enumerator in a foreach loop
$Home | User’s home directory
$Host | The application hosting PowerShell
$Input | Enumerator of objects piped to a script
$LastExitCode | Exit code of last program or script
$Matches | Hash table of matches found with –match.
$MyInvocation | Current cmd info, including scriptname.
$Null | Null or empty value – use in comparison test
$OFS | Output field separator. When defined, used to separate array elements -> string
$PSDebugContext | (v2) Indicates running debugger
$PSHome | The installation location of PowerShell
$PSScriptRoot | Directory of executing script module.
$profile | The standard profile (may not be present)
$StackTrace | Last exception caught by PowerShell
$Switch | Enumerator in a switch statement

System Variables affecting Exception Output

$ErrorActionPreference | Default: Continue
Non-term error: Continue, Stop, Inquire, SilentlyContinue
$ErrorView | Default: NormalView
NormalView | CategoryView – controls error output
$ReportErrorShowExceptionClass | Default: False.
If true, output the class name of exceptions.
$ReportErrorShowInnerException | Default: False.
If true, output the full chain of inner exceptions.
$ReportErrorShowSource | Default: True.
If true, output the assembly name for the source
$ReportErrorShowStackTrace | Default: False.
If true, output the stack trace of the exception.

Scripting

PowerShell commands can be stored in and executed from script files (extension “.ps1”).   Parameters can be passed to a script and a script can return a value.  
Example:
      $sum = MyAdder.ps1 1 2 3

Parsing

PowerShell parses in two modes—command mode and expression mode. In expression mode, PowerShell parses as most high-level languages parse: numbers are numbers; strings need to be quoted, and so on. Expressions are things such as: 
   "Hello" + " world"
   $a = "hi"
   $a.length * 13
When parsing in command mode, strings do not need to be quoted and everything is treated like a string except variables and things in parentheses. For example: 
   copy users.txt accounts.txt      
users.txt and accounts.txt are treated as strings
   write-host 2+2            
2+2 is treated as string, not an expression to evaluate
   copy $src $dest           
$src and $dest are variables. Not needing to use quotation marks when working in a command shell can be very beneficial in the long run because it greatly reduces the amount of typing required. 
The parsing mode is determined by the first token encountered. If the token is a number, variable, or quoted string, then the shell parses in expression mode. If the line starts with a letter, an & (ampersand), or a . (dot) followed by a space or a letter, the parsing is done in command mode. 
2+2 | Expression mode starts with a number.
"text" | Expression mode starts with a quotation mark.
text | Command mode starts with a letter.
& "text" | Command mode starts with an ampersand.
. "file.ps1" | Command mode starts with a dot followed by a space.
.125 | Expression mode starts with a dot, which is followed by a number—not a space or a letter.
.text | Command mode starts with a dot, which is part of the command name ".text"
It is very useful to be able to mix expressions and commands; which you can do by using parentheses. Inside parentheses, the mode discovery process starts over. 
Write-Host (2+2) 
2+2 is treated as an expression to evaluate and is passed to the Write-Host command.
(Get-Date).day + 2
Get-Date is treated as a command, and the result of executing it becomes the left value in the expression. 
You can nest commands and expressions without restrictions. 
Write-Host ((Get-Date).day + 2)
Get-Date is a command. ((Get-Date).day+2) is an expression, and Write-Host ((Get-Date).day + 2) is a command again. 
Write-Host ((Get-Date) - (Get-Date).date)
The Get-Date command is used twice to determine how much time has passed since midnight (condition).

Useful Script Settings

Set-PSDebug –Strict  - Detects references to uninitialized vars
Set-StrictMode –version Latest  - (v2) Uninitialized vars + more
---------------------------------------------------------------------------
Set-Executionpolicy  {Unrestricted | RemoteSigned | AllSigned | 
                                     Restricted | Default | Bypass | Undefined}
Enable-PSRemoting  - (v2) Enable remote execution

Testing and Debugging (v2) Commands

Measure-command {code} | Reports execution time
Set-PSBreakpoint  (sbp) | Sets breakpoints
Get-PSBreakpoint (gbp) | Gets breakpoints
Disable-PSBreakpoint | Disables breakpoints
Enable-PSBreakpoint | Re-enables disabled breakpoints
Remove-PSBreakpoint (rbp) | Removes breakpoints
Step-Into (s) | Executes the next statement
Step-Over (v) | Same, but doesn’t step into functions & invocations
Step-Out (o) | Continue until return to caller
Stop (q) | Quits the debugger
Continue (c) | Continues to next breakpoint
List (l) | List code at breakpoint
Get-PSCallStack (k) | Displays current call stack

Comments

# This is a comment because # is the first char of a token
$a = “something” # …as is this
<#
A multi-line comment in v2
#>

Break

The break commands exits a loop or switch. It can take an optional LABEL to break to
Example:
while (1)
{        $a = something
          if ($a –eq 1) break;
}

Continue

The continue statement continues the next iteration of a loop or with the next token in a switch without breaking out of it. Example:
while (1)
{               $a = something
	if ($a –eq 1) (continue)
	# This line is not reached unless $a != 1
}

Dot Sourcing

Dot sourcing allows running functions, script blocks, and scripts in the current scope rather than a local one. 
Examples:
. MyFunction

$a = {$x = Get-Process | Select –First 2}
. $a    #Evaluates the script block in the current scope

Execution Order
Windows PowerShell attempts to resolve commands in the following order: aliases, functions, cmdlets, scripts, executables, and normal files.
For

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

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

Foreach

[:label] 
foreach (identifier in collection) {}
Expression | foreach { $_ }
Expression | % { $_ }
Expression | foreach {BEGIN{} PROCESS{ $_ } END{}}
foreach-object [-Process] <ScriptBlock> 
                          [-Begin <scriptblock>] 
                          [-End <scriptblock>] [-InputObject <psobject>] 
Examples:
$i = 1,2,3
foreach ($z in $i) {Write-Object $z}
Get-Process |foreach {BEGIN{$x=1}
       PROCESS{$X++} 
       END{“$X Processes”}
}

If / elseif / else

if (condition) {…}
elseif (condition) {…}
else {…}

On the command line, the closing brace must be on the same line as elseif and else. This restriction does not apply to scripts

Functions

function MyFunction {
	write-object $args[0]
}

function test ([string]$label=”default label”,[int]$start=0)
{ BEGIN {$x=$start} 
   PROCESS {“$label: $_”’; $x++}  # for each obj in pipeline…
   END{“$x total”}
}

Parameters – Functions and Scripts

param( [type]$parameter1
            [,[type]$parameter2] [= default value] ] )
Specifies named parameters for a function or script.  Must be the first executable command of script or function.  Param keyword optional if parameter list immediately follows a function name.  

Unnamed parameters can be referenced via the $args array.

Filters

Filters are a shorthand way of writing a function with a PROCESS script block.
filter MyFilter {
	$_.name
}

Return

The return command exits the current script or function and returns a value.  
Example:
function foo {
	return 1
}

Switch

switch [-regex|-wildcard|-exact][-casesensitive] ( pipeline )  {
                                               or
switch [-regex|-wildcard|-exact][-casesensitive] -file filename  {
      "string"|number|variable|{ expression } { statementlist }
        default { statementlist }
 }
Break exits the switch completely.  Continue stops processing the current token but continues with the next item in the pipeline.

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

Throw

Throw provides the same functionality for scripts as the ThrowTerminatingError API does for cmdlets.  Throw takes a string, exception, or ErrorRecord as an argument.
Examples:
throw "Danger, Danger" # Creates runtime exception
    throw (new-object IO.FileNotFoundException)

Traps

Trap [ExceptionType] {  # $_ contains the error that was caught
    if (…)
{    Continue  #  continue at the script statement after the one 
           #  trap; $? is updated but no error record is generated 
} else  (…)
{      Break   #  rethrow the exception
}
#  Doing nothing will follow $ErrorActionPreference setting
}

Try … Catch … Follow (v2)

Try {
   … 
} Catch [Exception Type 1], [Exception Type 2] {   
   # $error contains the exception caught
   … 
} Catch [Exception Type 3] {  
   …        # vary code based on exception type
} Catch {  
   …        # w/o type, any other exceptions end up here.
} Follow {
   …   # Clean-up code that executes with success or failure.
}

Until
do  { … } until (condition)
While

[:label] while (condition) {  …   }

do { … } while (condition)