PowerShell – How to get Calculated value in Select-Object Expression

In PowerShell, we can use the Select-Object cmdlet to change the returned property names and values in the desired format. In this post, I am going to explain how to dynamically change property names and different ways to get calculated values.

PowerShell supports calculated properties with the help of a hashtable containing Name key to represent custom property name and Expression key to define a script block.  The expression script block allows the command to execute and generate the calculated value. You can also write condition checks such as IF ELSE statement, Switch case in the expression block.

Example property hash-table with Name and Expression

@{ Name = 'property_name';  Expression = { <# script_block #> }}

Join the value of two properties and return as single property

The below command concatenates the value of two string properties and returns the combined text in a single field with a custom property name.

Get-Process | Select-Object Id, @{Name='Process';  Expression={$_.ProcessName +'-'+ $_.MainModule.FileName}}

Sum the value of two number fields

The below command adds the value of two number attributes and returns the computed output as a single property.

Get-Process | Select-Object Id, @{Name='Memory'; Expression={$_.NPM + $_.PM }}

Use IF statement condition check and return custom value

The below command executes the if-else condition check in the expression block and returns the custom-defined text based on the successful condition.

Get-Process | Select-Object Id, @{Name='MemoryStatus'; Expression={ IF ($_.PM -gt 10000000) { ‘High’} Else {‘Normal’} }}

If Else Statement with logical operator

Get-Process | Select-Object Id, @{Name='MemoryStatus'; Expression={ IF ($_.PM -gt 10000000 -OR $_.NPM -gt 10000 ) { 'High'} Else {'Normal'} }}

Switch case in select expression

The below command uses the switch case inside the select object expression block and returns the value for the custom column based on a successful case statement.

Get-Process | Select-Object ProcessName,
     @{Name='MemoryStatus'; Expression={               
                switch ($_.PM) {
                    # High
                    {($_ -ge 10000000)} {'High'; break}
 
                    # Medium
                    {($_ -lt 10000000) -and ($_ -gt 1000000)} {'Medium'; break}
 
                    # Low
                    {($_ -lt 1000000)} {'Low'; break}
 
                    default {'Low'}
                }
            }
}

Note: In short, you could write the Name key as n and Expression key as e.

Get-Process | Select-Object Id, @{n='Process'; e={$_.ProcessName +'-'+ $_.MainModule.FileName}}
Advertisement

Leave a Comment