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 override the way that Windows PowerShell interprets your statements, so the following table lists the options available to you.

Windows PowerShell evaluation controls

Statement

Example

Explanation

Precedence control:( )

5 * (1 + 2)
(dir).Count

Forces the evaluation of a command or expression, similar to the way that parentheses are used to force the order of evaluation in a mathematical expression.

Expression sub-parse:$( )

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

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

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

Forces the evaluation of a command or expression, similar to the way that parentheses are used to force the order of evaluation in a mathematical expression.

However, a sub-parse is as powerful as a sub-program, and is required only when it contains logic and flow control statements.

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

List evaluation:@( )

PS >"Hello".Length
5
PS >@("Hello").Length
1

Forces an expression to be evaluated as a list. If it is already a list, it will remain a list. If it is not, PowerShell ...

Get Windows PowerShell Quick Reference 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.