Parser modes
The parser in PowerShell is responsible for taking what is typed into the console, or what is written in a script, and turning it into something PowerShell can execute. The parser has two different modes that explain, for instance, why strings assigned to variables must be quoted, but strings as arguments for parameters only need quoting if the string contains a space.
The parser modes are different modes:
- Argument mode
- Expression mode
Mode switching allows PowerShell to correctly interpret arguments without needing values to be quoted. In the following example, the argument for the Name
parameter only needs quoting if the name contains spaces:
Get-Process -Name pwsh
The parser is running in Argument mode at the point the pwsh
value is used and therefore literal text is treated as a value, not something to be executed.
This means that, in the following example, the second command is interpreted as a string and not executed:
Set-Content -Path commands.txt -Value 'Get-ChildItem', 'Get-Item'
Get-Command -Name Get-Content commands.txt
The second command in the preceding code therefore does not do anything.
To execute the Get-Content
command, the argument must be enclosed in parentheses:
Set-Content -Path commands.txt -Value 'Get-ChildItem', 'Get-Item'
Get-Command -Name (Get-Content commands.txt)
The code in parentheses is executed, and the parser is in Expression mode.
Another example of this can be seen when using an enumeration value. An enumeration is a list of constants described by a .NET type. Enumerations are explored in Chapter 7, Working with .NET:
PS> Get-Date [DayOfWeek]::Monday
Get-Date: Cannot bind parameter 'Date'. Cannot convert value "[DayOfWeek]::Monday" to type "System.DateTime". Error: "String '[DayOfWeek]::Monday' was not recognized as a valid DateTime."
If the value for the argument is placed in parentheses, it will run first and expand the value. Once the value is expanded, Get-Date
will be able to work with it:
Get-Date ([DayOfWeek]::Monday)
The help document, about_parsing
, explores this topic in greater detail.