I want to read a file line by line in PowerShell. Specifically, I want to loop through the file, store each line in a variable in the loop, and do some processing on the line.
I know the Bash equivalent:
while read line do
if [[ $line =~ $regex ]]; then
# work here
fi
done < file.txt
Not much documentation on PowerShell loops.
This question is related to
powershell
powershell-ise
The almighty switch
works well here:
'one
two
three' > file
$regex = '^t'
switch -regex -file file {
$regex { "line is $_" }
}
Output:
line is two
line is three
Get-Content
has bad performance; it tries to read the file into memory all at once.
C# (.NET) file reader reads each line one by one
Best Performace
foreach($line in [System.IO.File]::ReadLines("C:\path\to\file.txt"))
{
$line
}
Or slightly less performant
[System.IO.File]::ReadLines("C:\path\to\file.txt") | ForEach-Object {
$_
}
The foreach
statement will likely be slightly faster than ForEach-Object
(see comments below for more information).
I was able to read a 4GB log file in about 50 seconds with the following. You may be able to make it faster by loading it as a C# assembly dynamically using PowerShell.
[System.IO.StreamReader]$sr = [System.IO.File]::Open($file, [System.IO.FileMode]::Open)
while (-not $sr.EndOfStream){
$line = $sr.ReadLine()
}
$sr.Close()
Source: Stackoverflow.com