PowerShell を使用してディレクトリ内のファイルをループする 質問する

PowerShell を使用してディレクトリ内のファイルをループする 質問する

ディレクトリ内の 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

ベストアンサー1

これを試してみてください:

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')
}

おすすめ記事