Question

What I'm trying to do is create array variable names dynamically, and then with a loop, add the object to its relevant array based on the hash table value being equal to the counter variable.

$hshSite = @{}  # Values like this  CO,1  NE,2  IA,3

$counter = $hshSite.count

For($i = $counter; $i -gt 0; $i--) {
New-Variable -Name "arr$i" -Value @()
}

If $counter = 3, I would create arrays $arr1, $arr2, $arr3

$csv = Import-CSV....

ForEach ($x in $csv) {
   #if $hshSite.Name = $x.location (ie CO), look up hash value (1),
   and add the object to $arr1.  If $hshSite.Name = NE, add to $arr2

I tried creating the dynamic arrays with New-Variable, but having issues trying to add to those arrays. Is it possible to concatenate 2 variables names into a single variable name? So taking $arr + $i to form $arr1 and $arr2 and $arr3, and then I can essentially just do $arr0 += $_

The end goal is to group things based on CO, NE, IA for further sorting/grouping/processing. And I'm open to other ideas of getting this accomplished. Thanks for your help!

Était-ce utile?

La solution

Just make your hash table values the arrays, and accumulate the values to them directly:

$Sites = 'CO','NE','IA'
$hshSite = @{}
Foreach ($Site in $Sites){$hshSite[$Site] = @()}

ForEach ($x in $csv)
 {
   $hshSite[$x.location] += <whatever it is your adding>
 } 

If there's a lot of entries in the csv, you might consider creating those values as arraylists instead of arrays.

$Sites = 'CO','NE','IA'
$hshSite = @{}
Foreach ($Site in $Sites){ $hshSite[$Site] = New-Object Collections.Arraylist }

ForEach ($x in $csv)
 {
   $hshSite[$x.location].add('<whatever it is your adding>') > $nul
 } 

Autres conseils

You could quite easily do add items to a dynamically named array variable using the Get-Variable cmdlet. Similar to the following:

$MyArrayVariable123 = @()
$VariableNamePrefix = "MyArrayVariable"
$VariableNameNumber = "123"

$DynamicallyRetrievedVariable = Get-Variable -Name ($VariableNamePrefix + $VariableNameNumber)
$DynamicallyRetrievedVariable.Value += "added item"

After running the above code the $MyArrayVariable123 variable would be an array holding the single string added item.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top