Reputation: 590
so, first of all my scenario: Have a file, my script reads that file, counts the number of lines and reads the content line by line.
My script:
$lines = Get-Content C:\RDS\snaps.txt | Measure-Object -Line
$line = $lines.Lines
for($i=1; $i -le ($line-1); $i++)
{
#Need to store a line in a variable
}
I need to be in this way: For every "i" value which is less than or equal to ($line-1), I need to read the specific line.
Example: if i=1, means first line, I need to read the first line and store it in a variable. if i=($line-1), means the line above the last line, need to store that specific line and store it in the same variable.
How can this be done? I can't predict how many lines it will be there in the file. What change do I need to do in my script for this? Any help would be really appreciated.
Upvotes: 0
Views: 71
Reputation: 26130
this question is really not clear, but if you just want to read a specific line, you don't need a for loop. In fact get-content will return a collection (array) of object for each line. So the nth line can be accessed it with $content[n-1]
.
So
$content=Get-Content C:\RDS\snaps.txt
$content[0] #firstline
$content[-2]# the line before the last line
Upvotes: 1
Reputation: 58921
You could use a simple foreach loop to iterate over each line:
$Content = Get-Content 'C:\RDS\snaps.txt'
$lineCount = 0;
$lastLine = ''
foreach ($line in $content)
{
$lineCount++
# Insert your condition to store the lastline: if ($lineCount -eq ...)
$lastLine = $line
}
Upvotes: 2