PowerShell: How to Save Each Line of Text File as Array


Often you may want to save each line of a text file as an array in PowerShell.

You can use the following methods to do so:

Method 1: Use Get-Content

$my_array = @(Get-Content players.txt)

This particular example saves each line of the text file named players.txt into an array named $my_array.

By default, the Get-Content cmdlet in PowerShell returns each line from a text file as a separate string, so it will produce an array in which each element of the array is an individual line from the file.

Note that we use the @ symbol to ensure that the resulting object is an array.

Method 2: Use ReadAllLines

$my_array = [IO.File]::ReadAllLines('c:\users\bobbi\players.txt')

This particular example also saves each line of the text file named players.txt into an array named $my_array.

This method is much faster than the previous method because it uses the System.IO.File method ReadAllLines, which comes directly from the .NET framework.

Note that you must specify the absolute path when referring to a file using this method because .NET often has a different current directory than PowerShell.

The following examples show how to use each method in practice with a file named players.txt that contains information about various basketball players:

Example: How to Save Each Line of Text File as Array in PowerShell

We can use the following syntax with the Get-Content cmdlet to save each line of the text file named players.txt to an array in PowerShell:

$my_array = @(Get-Content players.txt)

The following screenshot shows how to use this syntax in practice:

PowerShell save each line of file as array

Notice that this returns an array in which each element of the array represents an individual line from the file.

By using bracket notation such as $my_array[0], $my_array[1], $my_array[2], etc. we are able to retrieve the first, second, third, etc. lines from the file.

Note that we could also use the ReadAllLines method directly from the .NET framework to save each line from the file as an array as well:

$my_array = [IO.File]::ReadAllLines('c:\users\bobbi\players.txt') 

The following screenshot shows how to use this syntax in practice:

Notice that this method also returns an array in which each element of the array represents an individual line from the file.

If you’re working with an extremely large file then it is recommended to use this method because it’s much faster than the previous method.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Compare Two Arrays
PowerShell: How to Create an Array of Arrays
PowerShell: How to Create an Array with Initial Size
PowerShell: How to Remove Duplicate Values from Array

Leave a Reply