Acerbity
Acerbity

Reputation: 527

How can I import a .csv into multiple arrays in a simpler way?

I am new to powershell and am writing my first somewhat complicated script. I would like to import a .csv file and create multiple text arrays with it. I think that I have found a way that will work but it will be time consuming to generate all of the lines that I need. I assume I can do it more simply using foreach-object but I can't seem to get the syntax right.

See my current code...

$vmimport = Import-Csv "gss_prod.csv"
$gssall = $vmimport | ForEach-Object {$_.vmName}`
$gssweb = $vmimport | Where-Object {$_.tier -eq web} | ForEach-Object {$_.vmName}
$gssapp = $vmimport | Where-Object {$_.tier -eq app} | ForEach-Object {$_.vmName}
$gsssql = $vmimport | Where-Object {$_.tier -eq sql} | ForEach-Object {$_.vmName}

The goal is to make 1 group with all entries containing only the vmName value, and then 3 separate groups containing only the vmName value but using the tier value to sort them.

Can anyone help me with an easier way to do this?

Thanks!

Upvotes: 0

Views: 3772

Answers (3)

Davor Josipovic
Davor Josipovic

Reputation: 5504

I like the Shay Levy way, but the values of hash tables remain hash tables. Here is an other more efficient approach where values are jagged arrays, and categories are made automatically (contrary to Ansgar Wiechers solution):

# define hashtable
$gs = @{};

# fill it
$vmimport | foreach {$gs[$_.tier]+=, $_.vmName};

# get web VMs
$gs['web'] # the result is an array of 'web' vmNames.

Upvotes: 0

Shay Levy
Shay Levy

Reputation: 126742

For the last three you can group the object by the Tier property and have the result as a hasthable. Then you can reference the Tier name to get its VMs.

#group objects by tier
$gs = $vmimport | Group-Object tier -AsHashTable

# get web VMs
$gs['web']

# get sql VMs
$gs['app']

Upvotes: 2

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200293

You may want to use a dictionary for storing the data:

$vmimport = Import-Csv "gss_prod.csv"

$gssall = $vmimport | % { $_.vmName }

$categories = "web", "app", "sql", ...
$gss = @{}
foreach ($cat in $categories) {
  $gss[$cat] = $vmimport | ? { $_.tier -eq $cat } | % { $_.vmName }
}

Upvotes: 0

Related Questions