Index your table. :)

Ever wanted to display format-table or select-object with index that you won’t have to calculate yourself? I did. Even though I don’t use ft very often. I played with it today a bit and came with rather simple solution:

PowerShell, using GeSHi 1.0.8.6
  1. $__counter = New-Object PSObject -Property @{Id=-1;Index=-1}
  2. $__indexFT = @{
  3.     Name=‘Index’
  4.     Expression={
  5.         if ($__counter.Id -ne $MyInvocation.HistoryId) {
  6.             $__counter.Index = 0
  7.             $__counter.Id = $MyInvocation.HistoryId
  8.         }
  9.         $__counter.Index
  10.         $__counter.Index++
  11.     }
  12.     Width = 6
  13.     Alignment = ‘Right’
  14. }
  15. $__indexSE = @{
  16.     Name=‘Index’
  17.     Expression={
  18.         if ($__counter.Id -ne $MyInvocation.HistoryId) {
  19.             $__counter.Index = 0
  20.             $__counter.Id = $MyInvocation.HistoryId
  21.         }
  22.         $__counter.Index;
  23.         $__counter.Index++
  24.     }
  25. }

Separate hast tables are there only because it’s illegal to use hash with not supported properties for that purpose, and because it looks nice in format-table if column has fine width and alignment. So all you had to do once you have it in module/ profile is:

gwmi win32_service | ft $__index, name, displayname => for good looking talbe or gwmi win32_service | select $__index, name. Should work fine in either way.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s