294

次のコードを変更して、1 つのファイルだけでなく、ディレクトリ内のすべての .log ファイルを確認するにはどうすればよいですか?

すべてのファイルをループして、「step4」または「step9」を含まないすべての行を削除する必要があります。現在、これにより新しいファイルが作成されますが、ここでループを使用する方法がわかりませんfor each(初心者)。

実際のファイルの名前は2013 09 03 00_01_29.logのようになります。出力ファイルを上書きするか、同じ名前に「out」を追加してください。

$In = "C:\Users\gerhardl\Documents\My Received Files\Test_In.log"
$Out = "C:\Users\gerhardl\Documents\My Received Files\Test_Out.log"
$Files = "C:\Users\gerhardl\Documents\My Received Files\"

Get-Content $In | Where-Object {$_ -match 'step4' -or $_ -match 'step9'} | `
Set-Content $Out
4

4 に答える 4

433

これを試してください:

Get-ChildItem "C:\Users\gerhardl\Documents\My Received Files" -Filter *.log | 
Foreach-Object {
    $content = Get-Content $_.FullName

    #filter and save content to the original file
    $content | Where-Object {$_ -match 'step[49]'} | Set-Content $_.FullName

    #filter and save content to a new file 
    $content | Where-Object {$_ -match 'step[49]'} | Set-Content ($_.BaseName + '_out.log')
}
于 2013-09-17T11:37:13.840 に答える
117

使用できるディレクトリのコンテンツを取得するには

$files = Get-ChildItem "C:\Users\gerhardl\Documents\My Received Files\"

次に、この変数もループできます。

for ($i=0; $i -lt $files.Count; $i++) {
    $outfile = $files[$i].FullName + "out" 
    Get-Content $files[$i].FullName | Where-Object { ($_ -match 'step4' -or $_ -match 'step9') } | Set-Content $outfile
}

これをさらに簡単に行うには、foreachループを使用します (@Soapy と @MarkSchultheiss に感謝):

foreach ($f in $files){
    $outfile = $f.FullName + "out" 
    Get-Content $f.FullName | Where-Object { ($_ -match 'step4' -or $_ -match 'step9') } | Set-Content $outfile
}
于 2013-09-17T10:23:56.313 に答える
40

特定の種類のファイルについてディレクトリ内を再帰的にループする必要がある場合は、次のコマンドを使用して、docファイル タイプのすべてのファイルをフィルタリングします。

$fileNames = Get-ChildItem -Path $scriptPath -Recurse -Include *.doc

複数のタイプでフィルタリングを行う必要がある場合は、次のコマンドを使用します。

$fileNames = Get-ChildItem -Path $scriptPath -Recurse -Include *.doc,*.pdf

$fileNames変数は、ビジネス ロジックをループして適用できる配列として機能します。

于 2016-04-28T15:23:59.720 に答える