PowerShell需求:创建包含N个子目录中最新文件最后一行的CSV列表
Hey there! Let's break down how to combine your existing PowerShell code snippets to achieve your goal of collecting the last line from the newest log file in each recently updated directory, then appending that data to a CSV.
Step-by-Step Solution & Combined Script
First, let's map out the core logic we need to implement:
- Fetch all log subdirectories updated in the last 1 day
- For each directory, locate the most recently modified log file
- Extract the final line of that file (efficiently, to avoid slowdowns with large logs)
- Package this data with context (like the server IP/directory name) and append it to a CSV
Here's the fully integrated script that handles all these steps:
# Define your base log directory and output CSV path $logRoot = "Z:\Logfiles" $outputCsv = "C:\Your\Desired\Path\LatestLogEntries.csv" # Process each recently updated directory Get-ChildItem -Path $logRoot -Directory | Where-Object { $_.LastWriteTime -gt (Get-Date).AddDays(-1) } | ForEach-Object { # Get the newest file in the current directory $newestFile = Get-ChildItem -Path $_.FullName -File | Sort-Object LastWriteTime -Descending | Select-Object -First 1 # Skip directories with no files to avoid errors if ($newestFile) { # Efficiently get the last line (uses less memory than reading the whole file) $lastLine = Get-Content -Path $newestFile.FullName -Tail 1 # Create a structured object for clean CSV output [PSCustomObject]@{ ServerIP = $_.Name # This will be your directory's IP address LogFileName = $newestFile.Name LastLine = $lastLine LogLastUpdated = $newestFile.LastWriteTime } } } | Export-Csv -Path $outputCsv -Append -NoTypeInformation -Encoding UTF8
Key Improvements & Explanations
-Directoryflag: Ensures we only target subdirectories underZ:\Logfiles, not any stray files in the root.Sort-Object -Descending | Select-Object -First 1: More efficient than sorting ascending and taking the last item—we stop processing as soon as we find the newest file.Get-Content -Tail 1: Far faster than reading the entire log file and usingSelect-Object -Last 1, especially for large log files (it only reads the final line directly).- PSCustomObject: Creates structured, labeled data so your CSV has clear columns (you can add/remove properties like
LogFileNamebased on what you need). Export-Csv -Append: Adds new entries to your CSV without overwriting existing content;-NoTypeInformationremoves the unnecessary type header line from the output.
Quick Notes
- If some directories might be empty, the
if ($newestFile)check skips them to prevent errors. - Adjust
$outputCsvto your preferred file path. - If you don't need extra columns like
LogFileNameorLogLastUpdated, simply remove them from thePSCustomObject.
内容的提问来源于stack exchange,提问作者DavDav
相关产品推荐
相关产品推荐

