PowerShell Sub-Expressions

This week I’m teaching a PowerShell Workshop and I get often asked why it is necessary to use a sub-expression, a $ sign followed by a set of parenthesis ().

Compare the following difference:

  1 $service = Get-Service -Name Spooler
 2 #Without the use of Sub-Expressions
 3 "The Spooler Service is currently $service.status"
 4 
 5 #Without the use of Sub-Expressions but extra step
 6 $status = $service.status
 7 "The Spooler Service is currently $status"
 8 
 9 #With the use of Sub-Expressions
10 "The Spooler Service is currently $($service.status)"

image

By using sub-expressions you are able to extract the value of a property for displaying. This saves the extra step of creating an additional variable to contain the value of the property before displaying it.

Hope this helps.