Appendix A. PowerShell Language and Environment

A.1. Commands and Expressions

PowerShell breaks any line that you enter into its individual units (tokens), and then interprets each token in one of two ways: as a command or as an expression. The difference is subtle: expressions support logic and flow control statements (such as if, foreach, and throw) while commands do not.

You will often want to control the way that Windows PowerShell interprets your statements, so Table A-1 lists the options available to you.

Table A-1. Windows PowerShell evaluation controls

Statement

Example

Explanation

Precedence control:( )

PS >5 * (1 + 2)
15
PS >(dir).Count
2276

Forces the evaluation of a command or 15 expression, similar to the way that paren-PS >(dir).Count theses are used to force the order of evalu2276 ation in a mathematical expression.

Expression subparse:$( )

PS >"The answer is (2+2)"
The answer is (2+2)

PS >"The answer is $(2+2)"
The answer is 4

Forces the evaluation of a command or The answer is (2+2) expression, similar to the way that parentheses are used to force the order of evaluation in a mathematical expression.

PS >$value = 10
PS >$result = $(
>>    if($value -gt 0) { $true }
>     else { $false }
>> )
>
PS >$result
True

However, a subparse is as powerful as a PS >$value = 10 subprogram, and is required only when it PS >$result = $( contains logic or flow control statements.

This statement is also used to expand dynamic information inside a string.

List evaluation: @()

PS >"Hello".Length ...

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

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.