Shell – Powershell: dynamic variables within foreach

environment-variablespowershell

I am trying to do some math for a dynamic list of users that I will use to run a search and count some results anonymously, then add to a running total per user. So, for instance:

$users = Get-ADUser -filter blah
[int]$usercount = $users.count

for ($z=1; $z -le $usercount; $z++) {
    **** create variable here - $user$z ***
}

When the variable is created, I need it available for further loops where I will add a count to the number already stored in the variable.

And no, I can't use the $user variable, because it must persist after this foreach loop ends.

So, the question is, how to I generate that incrementing variable not knowing the limit of the count of possible objects?

—EDIT—

Adding an easy example of what I am talking about…

After feedback, I am looking at hashtables, but still can't figure out how to reference.

Imagine a dice game between a dynamic list of people with multiple rounds. I want to increment per round their total. My problem is the last line where I try to update the total with the roll. How do I reference the hashtable value?

[CmdletBinding()]

param (
    [parameter(Mandatory=$false)][ValidateRange(1, [int32]::MaxValue)][int]$rounds = "15",
    [parameter(Mandatory=$false)][ValidateRange(1, [int32]::MaxValue)][int]$players = "2"
)

$ptotal = [ordered]@{}
for ($w=1; $w -le $players; $w++) {
    $ptotal.add("player$w", 0)
}

for ($z=1; $z -le $rounds; $z++) {
    Write-Host Round $z

    for ($y=1; $y -le $players; $y++) {

        $roll = (1..6 | get-random) + (1..6 | get-random)
        $ptotal.player$y = $ptotal.player$y + $roll
    }
}

Best Answer

in your example it would be $ptotal["player$y"] += $roll

You can use Hashtables both like associative arrays and objects. Very good reading about them is https://kevinmarquette.github.io/2016-11-06-powershell-hashtable-everything-you-wanted-to-know-about/ (on top of official documentation, of course)

Related Question