Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to put a counter column when doing Get commands in PowerShell?

I need to extract a Get command results into a CSV. The order column should be automatically generated upon a call and give each object its counter upon its appearance in the list. Would this be possible?

For example, when I’d do something like

Get-VMHost | Select @{N="Order";E={$suborder++}}, Name, Version, Build | Export-Csv -path .\smth.csv

I would like to get a result like

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Order Name        Version   Build   
----- ----        -------   -----   
    1 servername1   1.1.1   11111111
    2 servername2   1.1.1   11111111
    3 servername3   1.1.1   11111111

Would this be possible without using an array?

>Solution :

There are two problems with the current approach:

  1. Unary ++ doesn’t output anything by default
  2. Select-Object runs property expressions in their own scope, so you’re not actually updating $suborder, you’re creating a new local variable every time.

The first problem can be solved by wrapping the operation in the grouping operator (...):

... | Select @{N="Order";E={($suborder++)}}, ...

The second problem can be solved by obtaining a reference to an object that exposes the suborder value as a property.

You can either use a hashtable or a custom object to "host" the counter:

$counter = @{ suborder = 1 }

... | Select @{N="Order";E={($counter['suborder']++)}}

… or you can make PowerShell wrap the original variable in a PSRef-wrapper by using the [ref] keyword:

$suborder = 1

... | Select @{N="Order";E={(([ref]$suborder).Value++)}}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading