Search code examples
powershellcalculated-property

How do I add a computed column to get-service powershell output


I'd like to add a computed column to the get-service output based on the name. Let's say for this example, I'd like to take the Status column and substring it to show the first 3 characters in a new computer column called Name 2.

Tried the following but not getting expected behavior:


# Get all services
$services = Get-Service -Name BITS, appinfo

# Add a computed column
$servicesWithComputedColumn = $services | Select-Object *, @{Name='ServiceType'; Expression={ if ($_.StartType -eq 'Automatic') { 'rsAuto' } else { 'rsManual' } }}

# Display the result
$servicesWithComputedColumn

enter image description here


Solution

  • Preface:

    • The code snippet in your question tries to create a different calculated property than the one described verbally.

    • The syntax of that code snippet is correct in principle, but fails because the name of the calculated property collides with an existing property present on the input object.

      • To avoid this collision, add an -ExcludeProperty ServiceType argument to the Select-Object call.

    To answer your question as asked, using a calculated property:

    Get-Service -Name BITS, appinfo | 
      Select-Object *, @{
         Name = 'Name 2'
         Expression = { $_.Status.ToString().Substring(0, 3) }
      } |
      Format-Table Status, Name, 'Name 2', DisplayName
    

    Note the need to call .ToString() on $_.Status in order to perform a substring operation (.Substring()), because $_.Status latter is an instance of an [enum]-derived type, specifically [System.ServiceProcess.ServiceControllerStatus].

    Note that if you need the calculated property solely for display purposes, there is no need to use Select-Object (which you'd need for later programmatic processing), and you can instead use the calculated property directly with Format-Table