2016-10-11 8 views
0

私の目標は、スピードを考慮した正規表現を含むすべてのファイルをディレクトリから再帰的に検索することです。正確な一致が含まれている列を持つCSVに出力し、別の列に見つかったファイルを表示します。ユーザーwoxxomのおかげで、Select-Stringを使用するよりもはるかに速いので、IO.Fileで再生を開始しました。PowerShellを使ってRegexファイルとCSV出力ファイルをすばやく検索

これは私が長年取り組んできたプロジェクトで、Select-StringExport-Csvを使って達成できましたが、やや遅い処理です。

私の新しい試みには何が欠けているのでしょうか?

$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 
     } 
    } 
} 
+0

を書き込むことによって、パフォーマンスを高速化することができますか? – xidgel

+0

いいですよね、私はタグを削除しました。 – MrMr

+0

*「私の新しい試みで何が失われているのか?」* Dunno。期待どおりに動作しないのは何ですか? –

答えて

2

あなたは、これはExcelをタグ付けされるのはなぜ読み込むためにストリームを使用して

$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 

    $file2 = new-object System.IO.StreamWriter($ResultsCSV) #output Stream 
    $file2.WriteLine('Matches,File Path') # write header 

    foreach ($FileSearched in $TextFiles) { #loop over files in folder 

     # $text = [IO.File]::ReadAllText($FileSearched) 
     $file = New-Object System.IO.StreamReader ($FileSearched) # Input Stream 

     while ($text = $file.ReadLine()) {  # read line by line 
      foreach ($match in ([regex]$RX).Matches($text)) { 
        # write line to output stream 
        $file2.WriteLine("{0},{1}",$match.Value, $FileSearched.fullname) 
      } #foreach $match 
     }#while $file 
     $file.close(); 
    } #foreach 
    $file2.close() 
+0

それはトリックをした、私はこれがいかに速いか信じられない。これを手伝ってくれてありがとう! – MrMr

+0

最後に質問しますが、既存の出力ファイルを同じ形式で追加したい場合は、これを簡単に行うことができますか? – MrMr

+1

新しいファイルを作成したくない場合は、既存のファイルに追加することができます。 StreamWriter行を次のように変更します。$ file2 = new-object System.IO.StreamWriter($ ResultsCSV、$ true)#新しいファイルストリームを追加または作成します。 $ trueは新しいファイルが存在しない場合に作成することを意味します。 –

関連する問題