powershellforeachazure-powershellforeach-objectpowershell-az-module

How to make ForEach-Object start counting from 1 instead of 0


I have a nice string that looks like this:

Get-Azsubscription | ForEach-Object {"$($a).) $($_.Name)"; $a++}

It allows me to count how many subscriptions I have on Azure and it adds a number to it. The problem is that the counter starts from 0, which is in my case .) :

enter image description here

How to make that counter start to count from 1 and not from 0?


Solution

  • The ForEach-Object cmdlet takes an additional -Begin block you can use to initialize any variable you want to use:

    Get-Azsubscription | ForEach-Object -Begin { $a = 1 } -Process {"$a.) $($_.Name)"; $a++}