How to create and populate an array in Powershell based on a dynamic variable?

走远了吗. 提交于 2019-12-12 01:49:44

问题


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:


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"
}


来源:https://stackoverflow.com/questions/28242163/how-to-create-and-populate-an-array-in-powershell-based-on-a-dynamic-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!