4.1. Windows PowerShell's Two Command Line Parsing Approaches

One of the potentially confusing aspects for newcomers to Windows PowerShell when using the command line is that, on the command line, Windows PowerShell can parse in two ways: command mode and expression mode. To illustrate this, type the following at the command line:

2 + 2

The value 4 is displayed in the console. The expression 2 + 2 has been evaluated and then the result of the evaluation has been displayed in the console. This is expression mode. Next, type the following at the command line:

write-host 2 + 2

This time Windows PowerShell just wrote the string 2 + 2 to the console—Windows PowerShell performs no calculations. Figure 4-1 shows the two effects.

Figure 4.1. Figure 4-1

The preceding example demonstrates expression mode parsing for the first command and command mode parsing for the second. What do you do if you want Windows PowerShell to evaluate 2 + 2 in the second example? You can simply rewrite it as:

write-host (2 +2)

Inside parentheses, Windows PowerShell's parser makes a fresh start for deciding which parsing mode to use. The 2 + 2 inside the paired parentheses is treated as an expression and is parsed in expression mode, just as when 2 + 2 is written alone on the command line. So, the expression inside the paired parentheses is evaluated first, and the value that results is the argument to the ...

Get Professional Windows® PowerShell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.