PowerShell:在N个子目录中的最新文件中创建包含最新行的CSV列表 [英] Powershell: Create CSV list containing newest line in newest file in N number subdirs
本文介绍了PowerShell:在N个子目录中的最新文件中创建包含最新行的CSV列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在PowerShell方面相当新手,所以这对我来说是一个挑战:
目标:遍历包含日志的N个子目录,在每个子目录中找到最新的文件,提取最后写入的行并将其添加到文件中。
这列出了包含日志的目录--这些目录超出了我的控制范围。
Get-ChildItem Z:Logfiles | Where{$_.LastWriteTime -gt (Get-Date).AddDays(-1)}
我找到了这个代码片段,用于从命名目录中最后写入的文件中提取最后一行,其中每个目录包含来自名为文件夹名称的服务器的日志(主要是IP地址):
gci Z:Logfiles172.16.1.1 | sort LastWriteTime | select -last 1 | Get-Content | Select-Object -Last 1
我需要合并这些行,以便可以将最后这几行追加到文件中,可能是CSV-感谢所有提示。
推荐答案
您可以使用类似的内容,我添加了注释,以便更容易理解逻辑。
# List all folders on the Initial Path
$folders = Get-ChildItem -Directory -Path Z:Logfiles
$export = [system.collections.generic.list[pscustomobject]]::new()
foreach($folder in $folders)
{
# Get the newest file in each folder
$file = Get-ChildItem $folder -File | Sort-Object LastWriteTime -Descending | Select -First 1
# Read the content of the file and get the last line
$content = (Get-Content $file)[-1]
# Here you can create a new object that will be used to export to Csv
# As an example, i'll create an object with the File Name,
# Last Write Time and Last Line of the Content (This will be the CSV columns)
$export.Add(
[PSCustomObject]@{
FileName = $file.Name
LastWriteTime = $file.LastWriteTime
LastLine = $content
})
}
# After the loop finishes you can export the results to a Csv
$export | Export-Csv -NoTypeInformation -Path "Path/To/Export/Here.csv"
这篇关于PowerShell:在N个子目录中的最新文件中创建包含最新行的CSV列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文