Search code examples
powershellstreamreaderstreamwriter

Powershell write array using StreamWriter


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.


Solution

  • if you want really use an array try this :

    try
    {
    $reader = New-Object System.IO.StreamReader 'C:\temp\test.txt'
    $lines = @()
    
    while (($line = $reader.ReadLine()) -ne $null)  
    {  
    if ($line.StartsWith("2020")) { $lines += $line }
    }
    
    #not necessary to keep file open
    $reader.Close() 
    
    $writer = New-Object System.IO.StreamWriter 'C:\temp\test2.txt'
    $lines | %{$writer.WriteLine($_)}
    
    }
    finally
    {
    
        if ($reader -ne $null)
        {
            $reader.Close()
            $reader.Dispose()
        }
    
        if ($writer -ne $null)
        {
            $writer.Close()
            $writer.Dispose()
        }
    }
    

    otherwise :

    try
    {
    $reader = New-Object System.IO.StreamReader 'C:\temp\test.txt'
    $writer = New-Object System.IO.StreamWriter 'C:\temp\test2.txt'
    
    while (($line = $reader.ReadLine()) -ne $null)  
    {  
    if ($line.StartsWith("2020")) { $writer.WriteLine($line)}
    }
    
    }
    finally
    {
    
        if ($reader -ne $null)
        {
            $reader.Close()
            $reader.Dispose()
        }
    
        if ($writer -ne $null)
        {
            $writer.Close()
            $writer.Dispose()
        }
    }