Search notes:

PowerShell: Parsing commands and expressions

PowerShell has two parsing modes:
Expression mode which is used to parse expressions that possibly consist of sub-expressions
Argument mode which is used to parse command arguments
When PowerShell parses an input, it starts in expression mode. When a parsed token refers to a command invocation, parsing mode switches to argument mode.
When being in argument mode, there are a set of tokens that are evaluated in expression mode.

Expression mode

Expression mode recognizes the following token types:
Character string literals which are enclosed in single or double quotes
Number literals
Operators which start with a hypen (for example -gt or -as etc)
Attribute and conversion expressions [int] 42
Variable references which start with dollar sign ($foo). Variable references are evaluated as soon as they're encountered. (However, splatting is not possible)
A token that is not recognized as one of the listed above is assumed to refer to a command invocation.

Argument mode

In argument mode, the following characters and syntaxes have a special meaning:
$variable Only if name of variable exists
'verbatim' and "expandable" strings
(…) Parenthesis enclose an expression (which are evaluated in expression mode again)
$( … ) The subexpression operator
{ … } A script block
@ An initial at-sign starts splatting, arrays or hash tables
, commas create arrays
A token that is not recognized as one of the listed above is assumed to be an expandable string (that is: strings with double quotes rather than single quotes, see also this StackOverflow answer)

Example of a consequence of the differing parsing modes

For example, in the following example, the token [System.Text.Encoding] is not recognized as a type reference to System.Text.Ecoding, rather, the second argument to the constructor of System.IO.StreamWriter is passed the string "[System.Text.Encoding]::UTF8".
$outStream = new-object System.IO.StreamWriter some.file, [System.Text.Encoding]::UTF8
In expression mode, [System.Text.Encoding] would have been recognized as a type reference.

See also

The System.Management.Automation.Language.Parser class parses PowerShell script files and returns and instance of System.Management.Automation.Language.ScriptBlockAst.

Links

about_Parsing

Index