Line Numbers in PowerShell

For your Viewing pleasure, different methods to add line numbers to powershell output. Methods focused at adding the numbers to the default view of ;the Format-list command

Why add line numbers?

Why? – I’m tired of counting line numbers in powershell output.

I enjoy using the square brackets to select / view a specific line in powershell output / arrays.    Example – if I have a variable, $bob filled with a list of names I can add [0] to the end of $bob[0] and powershell will return the first line in the array. 0 = equals the first line, 1 is the second line, ETC. Normally I look at the screen and count the lines. Not anymore because I’m tired of doing that.

For more examples using the square brackets – see this old powershell tip

How to add line numbers

In my examples I am using the following basic command get-mailboxstatistics. My goal is to beable to use my thing with any command in any powershell session without having to load extra code or copy and paste lines of things from onenote.

$bob = Get-MailboxStatistics -IncludeMoveHistory

Method one

The results are close to covering my desires, but not cool because you must know what’s in the output and select it and that’s annoying to me. here are are taking the most difficult approach I could come with up to add a property to each line in the array that is $bob.

$l = 0
$bob.movehistory |forEach-Object {New-Object psObject -Property @{‘LineNumber’=$l;’Status’= $_.status; ‘Starttimestamp’ = $_.starttimestamp};$l ++} | ft


Method two

Method two I’m adding a number $i to to the full $_ stream from each line of the $bob array. Which is not what I’m after at all for the output. to make this work I’d need to pick one thing from $bob to look at $_.onething, or select want to looked before adding the number | select $_ onething, twothing, other thing |  then dig in deeper with the square brackets

$l = 0
$bob.movehistory | % {“$l $_”;$l++}


Method Three

Bailey took my first idea and implemented it correctly; Thanks Baliey. Here we are adding a new property to the line in the $bob array then we can format table the output and see what we want. Bonus I might be able to type this from memory after typing it a few times.

$l = 0
$bob.movehistory | %{$_ | Add-Member -NotePropertyName Line -NotePropertyValue $l -Force; $l++}
$bob.movehistory | ft



Leave a Reply