Powershell Calculated Properties As Variables

Most of us would be familiar with the normal syntax of calculated properties when used to change or add properties when piping an object through Select-Object.

In short, a calculated property is a hashtable containing the name of the property to return, and an expression in the form of a script block which generates the value we wish to obtain.

A good example where I recently used this was with the Get-NetTCPConnection cmdlet. This outputs all TCP sessions on the host, along with the PID that each connection is owned by (OwningProcess).

LocalAddress       LocalPort RemoteAddress      RemotePort State       AppliedSetting OwningProcess
------------       --------- -------------      ---------- -----       -------------- -------------       58045     104.18.x.x         443        Established Internet       11944

The PID isn’t the most useful way to show the owning process as it may be a short lived executable, by the time we find what process the PID is bound to, it may already be gone.

To overcome this, we can use a calculated property to immediately pull the process name.

Get-NetTCPConnection  | Select LocalAddress, LocalPort, RemoteAddress, State, @{Label="ProcName";Expression={(Get-Process -PID $_.OwningProcess | Select Processname).Processname}} | ft -AutoSize
LocalAddress LocalPort RemoteAddress   State       ProcName
------------ --------- -------------   -----       --------     59932 104.18.x.x      Established chrome

This is probably already common knowledge to anyone with PowerShell experience, but what I recently discovered was that the whole hashtable can be assigned to a variable, and the variable then used in the Select statement.

$ProcName = @{Label="ProcName";Expression={(Get-Process -PID $_.OwningProcess | Select Processname).Processname}}
Get-NetTCPConnection  | select LocalAddress, LocalPort, RemoteAddress, State, $ProcName | ft -AutoSize

This makes the code cleaner and more readable, especially when there are multiple or very long calculated properties.

If you enjoyed this post consider sharing it on , , , or , and .