0

I've been struggling with this for a couple of days, and I'm not sure how to conquer it. I need to do the following:

Import a csv of users with the following values:

ID, Name, Region

Create an array based on the Region values that I can then use to populate with ID's and Names with that region, ie.

Array_SEA

AA_SCOM, Adam Andrews, SEA

Array_OAK

BB_SCOM, Bob Barker, OAK

Here's the code I've got right now:

$list2 = ipcsv .\TSE_Contact_List.csv | sort-object BU

$arraylist =@()

foreach ($vitem in $list2)
{
$arraylist += New-Object PsObject -Property @{'Array' = "Array_" + $vitem.bu}
}
foreach ($varray in $arraylist)
{
$arr = new-variable -Name $varray
$arr.value += $varray.array
$arr
}

This produces the following error for records with a duplicate regions: New-Variable: A variable with name '@{Array=Array_SCA}' already exists.

I'm also getting the following when it tries to add values: Property 'value' cannot be found on this object; make sure it exists and is settable.

I get that I'm not actually creating arrays in the second section, but I'm not sure how to pass the output of the variable to an array name without turning the variable declaration into the array name, if that makes sense.

I've tried the following with hash tables, and it gets closer:

$list2 = ipcsv .\TSE_Contact_List.csv | sort-object BU

$arraylist =@{}

foreach ($vitem in $list2){$arraylist[$vitem.bu] = @()}

foreach ($record in $list2)
{
$arraylist[$vitem.bu] += ($record.SCOMID,$record.Name,$record.BU)
Write-host "Array: "
$arraylist[$vitem.bu]
write-host ""
}

The output on this shows no errors, but it just keeps showing the added fields for all of the records for each iteration of the list, so I don't think that it's actually assigning each unique BU to the array name.

1 Answers1

0

I like the hashtable-approach, but I would finetune it a little. Try:

$list2 = ipcsv .\TSE_Contact_List.csv | sort-object BU

$arraylist = @{}

foreach ($vitem in $list2){
    if($arraylist.ContainsKey($vitem.BU)) {
        #Array exists, add item
        $arraylist[($vitem.BU)] += $vitem
    } else {
        #Array not found, creating it
        $arraylist[($vitem.BU)] = @($vitem)    
    }
}

#TEST: List arrays and number of entries
$arraylist.GetEnumerator() | % {
    "Array '$($_.Key)' has $($_.Value.Count) items"
}

You could also use Group-Object like:

$list2 = ipcsv .\TSE_Contact_List.csv | Group-Object BU

#TEST: List groups(regions) and number of entries
$list2 | % {
    "Region '$($_.Name)' has $(@($_.Group).Count) items"
}
Frode F.
  • 52,376
  • 9
  • 98
  • 114
  • 1
    Why not both? $list2 = ipcsv .\TSE_Contact_List.csv | Group BU -AsHashTable -AsString #TEST: List groups(regions) and number of entries $list2.getenumerator() | % { $_.key "-" $_.value | out-string } This method is great, and gets me off to a great start, thank you! Now I just need to figure out how to pull the values back out and pipe them to another cmdlet. – user1628184 Jan 30 '15 at 20:53