6

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.

2 Answers 2

19

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
Sign up to request clarification or add additional context in comments.

2 Comments

Nice, I hadn't seen this before.
This is how multiple assignment works in PowerShell. If you assign two values, the first parameter gets the first value and so on. But if the values being assigned are greater than the variable count then all remaining values are accumulated in the last variable.
6
$contents = gc .\myfile.txt

write-host $contents[0]

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.