Read a delimited file into an array

walden systems, powershell, array, delimited
PowerShell is a task-based command-line shell and scripting language built on .NET. PowerShell helps system administrators and power-users rapidly automate tasks that manage operating systems (Linux, macOS, and Windows) and processes. PowerShell commands let you manage computers from the command line. PowerShell providers let you access data stores, such as the registry and certificate store, as easily as you access the file system. PowerShell includes a rich expression parser and a fully developed scripting language.

Reading in a comma separated file or any delimited file into an array using Microsoft's PowerShell that is built into Windows 7, 8, 8,1 and 10 is straight forward once you are familiar with the commands. To start PowerShell, click on Start -> find and type in "PowerShell" ( without the quotes ). Windows PowerShell will show up. Right click on Windows PowerShell and click on Run as Administrator, this will bring up Windows PowerShell.

In order to do this, we will be using Import-CSV. Import-CSV reads in a file and separates the data by a delimiter, if a delimiter is not given, it will separate by ",". The first line in the file to be read in must have a header. This header will determine how the array will be accessed. Given the following file in C: empfoo.csv:

foo|Bar|
data1|data2
data3|data4


When you run the command:

$array1 = Import-CSV -Path C: empfoo.csv -Delimiter "|"

The data from the csv file will be stored in the array $array1. In this case, it is a two dimensional array


To get the number of items in the array, you can use

$array1.count

This will return the number of elements in the array, in the example above, it will return 2


To get the first dimension in the array, you can use

$array1.HEADER1
      or
$array1.HEADER2
      or
$array1.HEADERN

This will return the elements in the first column, second column, etc.

To get any row, you can use the following which will return the elements in ROW_NUMBER_N

$array1[ROW_NUMBER_N]