I'm new to PowerShell and am trying to write a script that will allow me to read through a very large text file and extract certain lines if they begin with "2020".
When a match is found, it should write to an array ($Lines), then I'm trying to output this filtered content to another text file using StreamWriter.
Here is what I have so far:
$reader = New-Object System.IO.StreamReader 'C:\Users\PSTest\Years.txt'
$writer = New-Object System.IO.StreamWriter 'C:\Users\PSTest\Data.txt'
$lines = @()
Foreach ($line in $reader) {
if ($reader -ne $null) {
while (!$reader.EndOfStream) {
$line = $reader.ReadLine()
if ($line.StartsWith("2020")) {
$lines += $line }
$writer.writeline($lines) }
}
}
$reader.dispose()
$writer.dispose()
When I write to the console I can tell there are hundreds of matches, but nothing ever gets written to the output file (Data.txt).
What am I missing? Thank you in advance.