PowerShell Sub-Expressions

PowerShell Sub-Expressions

  • Comments 5
  • Likes

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.

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment
  • Thanks, I didn't know this one yet.

  • Hi stefan,

    Great TIP! Thanks. Most of the time is was constructing a [string] with the {x} and the -f for this. till now ;-)

    Maybe you can help me out with a other mystery ?

    how do i read out the  IsManagementServer property on the example below ??

    $X= Get-SCOMClass -Name "Microsoft.SystemCenter.ManagementServer" | Get-SCOMMonitoringObject

    $.[Microsoft.SystemCenter.HealthService].IsManagementServer ??????

    $.IsManagementServer ??????

    [Microsoft.SystemCenter.HealthService].AuthenticationName                            : MAM.stateview.local

    [Microsoft.SystemCenter.HealthService].MaximumQueueSize                              : 104857600

    [Microsoft.SystemCenter.HealthService].MaximumSizeOfAllTransferredFiles              : (null)

    [Microsoft.SystemCenter.HealthService].RequestCompression                            : True

    [Microsoft.SystemCenter.HealthService].CreateListener                                : True

    [Microsoft.SystemCenter.HealthService].Port                                          : 5723

    [Microsoft.SystemCenter.HealthService].IsRHS                                         : True

    [Microsoft.SystemCenter.HealthService].IsManagementServer                            : True

    .....

    michel

  • Hi , figured it out.

    $x | GM

    pointed out it was a noteproperty

    since its using [] i have to use '' to make a string of it

    So the correct syntax would be

    $x.'[Microsoft.SystemCenter.HealthService].IsManagementServer'.value

    thanks anyway.

    Michel  

  • Hi Michel,

    You beat me :-) Great you solved it already.

    /Stefan

  • in unix its quote popular and is called command substitution. I discovered this through a very pedestrian occasion. I wanted to create ramdrive inside the OS X installer to store the logfile in ddrescue. The guide to create the ramdrive used the ` ...` notation in bash.