Powershell Arrays

      No Comments on Powershell Arrays

Arrays are quite useful and Powershell makes it really easy working with these.
An array is basically an bunch of elements grouped together. Rather than having $a=1; $b=2, we can have $myArray = @(1,2)
Managing a considerable amount of servers/hosts/vms with arrays makes anybody’s life easier.

Down to business!

Simple way to create an array in Powershell:
$groups = @("group1","group2","group3")

Dump $groups output:

Look at the example below:
This example assumes a csv delimited file (data.csv) by “;”.
If you use different delimiter for your CSV files that is fine, just update the -Delimiter parameter accordingly.

In this example we will end up with $data array which can have each of the CSV columns as different member that we can call/update individually, ie. $data.column1, $data.column2.

For simplicity sake lets assume a csv with a single column and no header with content similar to our $groups array above:
$data=Import-Csv .\data.csv -Delimiter ";"

This is great, but what do we do with it?
Well we can iterate through it, for each array member, do whatever we need to have done!

foreach ($arraymember in $groups) {if ($arraymember -eq "group3") {write-host "found my group: "$arraymember}}

Output for this would be: found my server: group3

Leave a Reply

Your email address will not be published. Required fields are marked *