PowerShell – Adding a Sequence column to your result

I just the little things that can help while collecting information using PowerShell.  This is one thing that can be reuse in so many ways and is just a matter of using one simple concept.

Let say you want to collect a list of files and at the same time you want to create a sequence# column to be included with this list and at the same time you know the total number listed.

Here’s my way I’m doing it:

1.  First, we are going to create a PowerShell “Global” variable:

$Global:sequence = 1;

2.  Then, we add the command (or could be another PowerShell variable holding the results).  In this example I’m using “dir” to get the list of all “name” and include a sequence column using custom Expression scriptblock:

$Global:sequence = 1; dir | Select @{label = “Seq”; Expression = {$Global:sequence; $Global:Sequence++;}}, Name | Format-Table -Autosize;

Now the trick is simple.  You define a global variable which will retain the incremental value produce inside the scriptblock in the “.. Expresion = {..}”.

Basically, just reuse the scriptblock “@{Label = “seq”; Expression = {$Global:Sequence; $Global:Sequence++;}}” in your PowerShell “Select” command.

Here’s a similar result:

Full code:

$Global:sequence = 1; dir | `
 Select `
 @{Label = “Seq”; Expression = {$Global:seq; $Global:seq++;}}, `
 Name | Format-Table -Autosize;

%d bloggers like this: