如何更改以下代码以查看目录中的所有 .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
试试这个:
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')
}
要获取目录的内容,您可以使用
$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
}
foreach ($f in Get-ChildItem "C:\Users\gerhardl\Documents\My Received Files\") { ... }
ForEach ($f in $files){...}
如果您需要在目录中递归循环以查找特定类型的文件,请使用以下命令,该命令会过滤 doc
文件类型的所有文件
$fileNames = Get-ChildItem -Path $scriptPath -Recurse -Include *.doc
如果您需要对多种类型进行过滤,请使用以下命令。
$fileNames = Get-ChildItem -Path $scriptPath -Recurse -Include *.doc,*.pdf
现在,$fileNames
变量充当 数组,您可以从中循环并应用您的业务逻辑。
-Force
参数。请参阅 docs.microsoft.com/en-us/powershell/module/… 处的文档。
其他答案很好,我只想添加......在 PowerShell 中可用的不同方法:安装 GNUWin32 实用程序并使用 grep 查看行/将输出重定向到文件 http://gnuwin32.sourceforge.net/
这每次都会覆盖新文件:
grep "step[49]" logIn.log > logOut.log
这会附加日志输出,以防您覆盖 logIn 文件并希望保留数据:
grep "step[49]" logIn.log >> logOut.log
注意:为了能够在全局范围内使用 GNUWin32 实用程序,您必须将 bin 文件夹添加到系统路径中。
不定期副业成功案例分享
FullName
替换BaseName
,我会得到我想要的。