title: Use PowerShell to Quickly Search Files for Regex and Output to CSV
body: <p>My goal is to search a directory recursively for all files that contain a regular expression with speed in mind. Then output to a CSV that has a column that includes the exact matches and another column shows the file they were found it. Thanks to the user woxxom, I've started playing with the <code>IO.File</code> as it's apparently much faster than using <code>Select-String</code>.</p>
  
  <p>This is a project I've been working on for a long time and was able to accomplish via <code>Select-String</code> and using <code>Export-Csv</code>, but it's a rather slow process.</p>
  
  <p>Any thoughts on what I'm missing with my new attempt?</p>
  
  <pre><code>$ResultsCSV = "C:\TEMP\Results.csv"
  $Directory = "C:\TEMP\examples"
  $RX = "(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?:\.|dot|\[dot\]|\[\.\])){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"
  $TextFiles = Get-ChildItem $Directory -Include *.txt*,*.csv*,*.rtf*,*.eml*,*.msg*,*.dat*,*.ini*,*.mht* -Recurse
  $out = [Text.StringBuilder]
  
  foreach ($FileSearched in $TextFiles) {
      $text = [IO.File]::ReadAllText($FileSearched)
      foreach ($match in ([regex]$RX).Matches($text)) {
          if (!(Test-Path $ResultsCSV)) {
              'Matches,File Path' | Out-File $ResultsCSV -Encoding ASCII
              $out.AppendLine('' + $match.value + ',' + $FileSearched.fullname)
              $match.value | Out-File $ResultsCSV -Encoding ascii -Append
              $FileSearched.Fullname | Out-File $ResultsCSV -Encoding ascii -Append
              $out.ToString() | Out-File $ResultsCSV -Encoding ascii -Append -NoNewline
         }
      }
  }
  </code></pre>