294

How can I change the following code to look at all the .log files in the directory and not just the one file?

I need to loop through all the files and delete all lines that do not contain "step4" or "step9". Currently this will create a new file, but I'm not sure how to use the for each loop here (newbie).

The actual files are named like this: 2013 09 03 00_01_29.log. I'd like the output files to either overwrite them, or to have the SAME name, appended with "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 回答
-15

其他答案很好,我只想添加......在 PowerShell 中可用的不同方法:安装 GNUWin32 utils 并使用 grep 查看行/将输出重定向到文件http://gnuwin32.sourceforge.net/

这每次都会覆盖新文件:

grep "step[49]" logIn.log > logOut.log 

这会附加日志输出,以防您覆盖 logIn 文件并希望保留数据:

grep "step[49]" logIn.log >> logOut.log 

注意:为了能够在全局范围内使用 GNUWin32 实用程序,您必须将 bin 文件夹添加到系统路径中。

于 2015-05-11T08:30:35.183 回答