次の方法で共有


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.

Comments

  • Anonymous
    September 25, 2013
    Thanks, I didn't know this one yet.

  • Anonymous
    October 30, 2013
    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

  • Anonymous
    November 05, 2013
    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  

  • Anonymous
    November 05, 2013
    Hi Michel, You beat me :-) Great you solved it already. /Stefan

  • Anonymous
    December 10, 2014
    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.