Windows PowerShell Parse Methods
Windows PowerShell parses in two modes—command mode and expression mode. In expression mode, Windows PowerShell parses as most high-level languages parse: numbers are numbers; strings need to be quoted, and so on. Expressions are things such as:
2+2
4
"Hello" + " world"
Hello world
$a = "hi"
$a.length * 13
26
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).
Posted in: .NET Framework MS Windows| Tags: Windows PowerShell Command Windows PowerShell parse expression mode numbers strings quoted Get-Date Write-Host condition