Search code examples
arrayspowershellforeachinitializationforeach-object

Initialize Array forEach line in a variable in PowerShell


I am trying to initialize arrays for each unique department in a CSV file. So far I have this and it doesn't seem to be working as intended.

$Org = Import-Csv Org.csv

$Dept_Unique = $Org.Department | Select-Object -Unique

This gives me the correct output and will list all the unique values of all departments in the CSV.

Accounting Team
Human Resources
Information Technology

Then I try to initialize an array for each of the departments with just some random values.

$Dept_Unique | ForEach-Object {
     $_ = @('User1','User2','User3')
}

My expected output would be...

${Human Resources}[1]
User2

However, I'm getting Cannot index into a null array.. Which tells me that array is not initializing how I want it to. Any help would be greatly appreciated, thanks!


Solution

  • If you want to create a new variable named after a value stored in a different variable, use New-Variable:

    $Dept_Unique | ForEach-Object {
        New-Variable -Name $_ -Value @('User1', 'User2', 'User3')
    }
    

    ... but I suspect what you really want is just to group all user names based on department - for this you'll want to use the Group-Object cmdlet instead of Select-Object -Unique (the following assumes you have a Username column in your csv):

    $Org |Group-Object Department |Select-Object @{Name='Dept';Expression='Name'},@{Name='Users';Expression={ @($_.Group.Username) }}
    

    This will create one object per unique Department value, with two properties: Dept (the department name) and Users, an array of usernames associated with the department