Msh Language Quick Start



Arithmetic Operators (also see Unary and String operators)


addition, concatenation




multiplication, string repetition





Array Comparison

Return all elements equal to 3:

1,2,3,5,3,2 –eq 3


Return all elements less than 3:

1,2,3,5,3,2 –lt 3


Test if 2 exists:

if (1, 3, 5 –eq 2) …


Other operators:  -gt, -le, -ge




array of strings


array of integers


empty array

\@(2) or ,2

array of 1 element


array within array


sixth element of array*


fourth element or the third


element of an array

* Arrays are zero-based.

Assignment Operators


Assigns a value to a variable


Adds a value to a variable


Subtracts a value from a variable


Multiplies a variable by a value


Divides a variable by a value


Performs a modulus on a variable

Associative Arrays (Hashtables)

$hash = \@{ }

Create empty hashtable


$hash.key1 = 1

Assign 1 to key "key1"


Returns value of key1



Returns value of key1



Assign code block to key1



Run code block in key1 with parameters 1,2


Boolean Values

$true = 1 –eq 1

Assigns True to $true

1,2,3 –and $true


$() –and $true


\@() –and $true


\@(1) –and $true


"" –and $true


"word" –and $true


break (scripting)

The "break" commands exits a loop.  Example:

while (1)


            $a = something

            if ($a –eq 1) break;


Command Expansion Operators

$( )

Returns null


Returns 1


Returns an array : 1,2,3.


Executes the two commands and returns the results in an array


# This is a comment.

$a = "#This is not a comment…"

$a = "something" # …but this is.

Comparison Operators

-band, -bor

bitwise and, bitwise or


regex pattern matching


globbing pattern matching

-eq, -ne

Equal, Not equal

-gt, -ge

Greater than, greater or equal

-lt, -le

Less than, less or equal


compare types (1 -is [int])

Case Insensitive variants

-imatch, -inotmatch, -ilike, -inotlike, -ieq,  -ine, -igt, -ige, -ilt, -ile

continue (scripting)

The continue statement continues the next iteration of a loop without breaking out of it.  Example:

while (1)


            $a = something

            if ($a –eq 1) (continue)

            # This line is not reached unless $a == 1


This line is never reached.

Dot Sourcing

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

. MyFunction

If MyFunction sets a variable, it is set in the current scope rather than the function’s local scope.

Escape Character and Escape Sequences

The MSH escape character is the backwards apostrophe, or `.  To make a character literal, precede it with `.  To specify a ` use ``.

Special escape sequences








(form feed)


(new line)


(carriage return)




(vertical quote)

Execution Order

MSH attempts to resolve commands in the following order:  aliases, functions, cmdlets, scripts, executables, normal files



for (scripting)

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



for ($i = 0; $i –lt 5; %i++) {write-object $i}


foreach (scripting)

[:label] foreach (identifier in pipeline or collection) {}



$i = 1,2,3

foreach ($z in $i) {write-object $z}


functions (scripting)

function MyFunction {

            write-object $args[0]


Filters (scripting)

filter MyFilter {




if/elseif/else (scripting)

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 exist for scripts


Invoke Operator

The & operator can be used to invoke the contents of an object.  Example:

$a = "get-process"


$a = { get-process | pick-head 2 }


Logical Operators

and -not

Not a single value


And two values


Or two values


Method Calls

Methods can be called on objects.  Examples:

$a = "This is a string"




$a.Substring(($a.length/2), ($a.length/3))

Static methods may be called as well:

[string].format("{0} {1} {2}","one",2,(get-date))

MSH Variables

Variables are case insensitive and case preserving.


contains the last token of last line input into the shell


Contains that success/fail status of the last operation


contains the first token of the last line input into the shell


The action to take when data is written via write-debug in a script or WriteDebug in a cmdlet or provider.


Number of entries saved in the command history.


The paths where .cmdlet and .cmdletprovider files may be found.  This is the msh equivalent of the CMD.EXE $PATH.


The paths where executables may be found.  These may be any existing Windows executable or .cmdlet or .cmdletprovider file.


Set to true indicates that the class name of the exception(s) displayed will be shown.

Default at internal startup is false.


Set to true indicates that the chain of inner exceptions should be shown.  Each exception message will be indented from the previous message.

The display of each exception is governed by the same options as the root exception, meaning that the options dictated by $ReportShowError* will be used to display each exception.

Default is false.


Set to true indicates that the assembly name from whence the exception originated will be displayed.

Default at internal startup is true.


Set to true indicates that the stack trace of the exception will be emitted. 

Default at internal startup is false.


The action to take when ShouldProcess is used in a cmdlet.


ShouldProcess will return this setting


The action to take when data is written via write-verbose in a script or WriteVerbose in a cmdlet or provider.


The current pipeline object, used in script blocks and where


Used in creating functions that require parameters


Objects which had an error occur while processing that object in a cmdlet.


The action to take when data is written via write-error in a script or WriteError in a cmdlet or provider.


Reference to the enumerator in a foreach loop


The users home directory; set to %HOMEDRIVE%\%HOMEPATH%


Can aid in code blocks that are in the middle of a pipeline, (see code block)


The install location of MSH


Information about the current executing host


Output Field Separator


contains detailed stack trace information about the last error.





Object Properties

An object’s properties can be referenced directly with the "." operator.

$a = get-date



Operator Precedence

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


The > and >> operators redirect command output to files.  The > operator creates a new file or truncates and existing one, while the >> operator appends to an existing file.  Example:

1,2,3 >foo.txt

5,6 >>foo.txt

return (scripting)

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

function foo {



Script Blocks

Commands and expressions can be stored in a script block object and executed later.  Example:

$block = {get-process; $a=1}



MSH commands can be stored in and executed from script files.  The file extension for MSH scripts is ".msh".  Parameters can be passed to a script and a script can return a value.  Example:

$sum = MyAdder.msh 1 2 3

Strings and String Operators

String constants:

"this is a string, this $variable is expanded"

‘this is a string, this $variable is not expanded’

String operators


Concatenate two strings


Repeat a string some number of times


Format a string


replace elements in a string


MSH>  "test" + "this"


MSH>  "{0:M}" -f $(get-date)

June 02

MSH> $a = 1,2,3,4

MSH> $a





MSH> $OFS = ":"

MSH> "$a"


MSH> "This is a test" -replace "is","IS"

ThIS IS a test


$a = 3

switch ($a) {

   1 {"got one"}

   2 {"got two"}

   3 {"got three"}


$var = "word2"

switch -regex ($var) {

   "word2"  {"Multi-match Exact " + $_ }

   "word.*" {"Multi-match Exact1 " + $_ }

   default  {"Multi-match Default " + $_; break}

   "w.*" {"Previous Break terminated the matching"}


$var = "word1","word2","word3"

switch -regex ($var) {

   "word1"  {"Multi-match Exact " + $_ ; continue}

   "word2"  {"Multi-match Exact " + $_ ; continue}

   default  {"Multi-match Default " + $_; continue}



Execute a block of code in a terminating error condition.  Example:

function handler1 { write-host "Hi, I'm a trap handler" }

function handler2 { write-host "Hi, I'm a trap handler2" }

trap [System.Management.Automation.ExecutionFailedException]

{ handler2 ; continue }

trap [System.Management.Automation.ExecutionBreakOnErrorException]

{ handler1 ; continue }

get-content thisisabadfilename -errorp notifystop

set-location thisisabadlocation

Types & Casts

Brackets around a string indicate a type object


cast object to type

$a = [int]"3"

$a + 3


"System" may omitted

Act on a type [IO.FileVersionInfo].GetMembers()

Unary Operators


Increment a variable


Decrement a variable


Indicate that a number is positive


Indicate that a number is negative





$a = 1

$global:a = 1

$local:a = 1

$env:path = "d:\windows"

            Scope may be either global, local or script

while (scripting)

[:label] while (condition)