File tree Expand file tree Collapse file tree 2 files changed +58
-0
lines changed
docs/document/Skill/PowerShell/docs/Language Expand file tree Collapse file tree 2 files changed +58
-0
lines changed Original file line number Diff line number Diff line change 1+ # Expression
2+
3+ ## Expression Grouping
4+
5+ ` () ` is grouping expression that allows ** assignment** /add higher execution ** precedence** within it and ** pass through the value to outer context.**
6+ It's worth noting that ` () ` does not allow to eval a control flow statement which is very counter-intuitive.
7+
8+ ``` ps1
9+ # enforce precedence
10+ (1 + 2) * 3 # 9
11+ # inline assignment
12+ ($foo = 1) # 1
13+ # eval a statement
14+ ($null = if ($true) { "foo" }) # foo
15+
16+ (if ($true) { "foo" }) # parsing error! # [!code error]
17+ ```
18+
19+ > [ !IMPORTANT]
20+ > ` () ` only allows one single expression within it.
21+
22+ ## Sub-Expression
23+
24+ ` $() ` is yet another way to eval a expression to value but suppress the output of assignment statement.
25+
26+ ``` ps1
27+ $(if ($true) { "foo" }) # foo
28+
29+ # assignment does not pass through value to outer context
30+ $($foo = 1 -gt 3) # $null
31+
32+ # self increment is another special kind of assignment
33+ $($i++) # $null
34+ ```
35+
36+ Since ` $() ` has a nature of suppressing value from assignment statement, we can use it as a single calculation block.
37+
38+ ``` ps1
39+ $foo = 1
40+ # custom calculation block
41+ $(
42+ $foo = 1 + 2
43+ # self operation is also suppressed even though it should output
44+ $foo++
45+
46+ $foo
47+ $foo # yield more than once
48+ ).Length # 2
49+ ```
50+
51+ ### Array Sub-Expression
52+
53+ ` @() ` is almost the same as ` $() ` but ensures the output as an array, no matter how few items were popped from the expression.
54+
55+ ``` ps1
56+ @($pwd).GetType().Name # Object[]
57+ $($pwd).GetType().Name # PathInfo
58+ ```
You can’t perform that action at this time.
0 commit comments