RichGK
RichGK

Reputation: 560

Read first line of text file then pass following lines to a loop to read

I need to read the first line of a file and then the subsequent lines I want read using a loop.

eg:

Read in first line
Do stuff with the data

foreach ($line in $remainingLines)
{
    more stuff
}

I have a rather messy way to achieve this but there must be a better way.

Upvotes: 6

Views: 10308

Answers (2)

aphoria
aphoria

Reputation: 20179

$contents = gc .\myfile.txt

write-host $contents[0]

for ($i=1; $i -lt $contents.Length; $i++)
{
  write-host $contents[$i]
}

Upvotes: 6

Shay Levy
Shay Levy

Reputation: 126722

Assign the content of the file to two variables. The first one will hold the first line, and the second variable gets the rest. Then loop over $remainingLines.

$firstLine,$remainingLines = Get-Content foo.txt

Upvotes: 19

Related Questions