Search code examples
arrayspowershellfile-iolinepowershell-cmdlet

How to save each line of text file as array through powershell


If I have a text file, C:\USER\Documents\Collections\collection.txt that has the following information:

collectionA.json
collectionB.json
collectionC.json
collectionD.json

I am wondering how, through Powershell, I am able to store each line in the text file as elements of an array such as..

array arrayFromFile = new Array;
foreach(line x in collection.txt)
{
    arrayFromFile.Add(x);
}

..with the end goal of doing the following:

foreach(string x in arrayFromFile)
{
    newman run x;
}

My apologies for the seemingly easy question - I have never dealt with Powershell before.


Solution

  • The Get-Content command returns each line from a text file as a separate string, so will give you an array (so long as you don't use the -Raw parameter; which causes all lines to be combined to a single string).

    [string[]]$arrayFromFile = Get-Content -Path 'C:\USER\Documents\Collections\collection.txt'
    

    In his excellent answer, mklement0 gives a lot more detail on what's really going on when you call this command, as well as alternate approaches if you're concerned about performance over convenience. Definitely worth a read if you're interested in learning more about the language rather than just solving this one off requirement.