如何在PowerShell中解析含AM/PM的时间戳文本行并过滤?
Let's get this sorted out for you! The issue with your original code is twofold: your regex wasn't accounting for the AM/PM suffix, and it was forcing two-digit months/days (but your logs use single-digit values like 9/1/2016). Here's how to fix it:
First, Fix the Regex Approach
Your original regex missed the AM/PM portion, which meant the extracted timestamp string was incomplete—so converting it to a [datetime] object failed silently. Let's update the regex to match your actual log format:
# Updated code with corrected regex Get-Content .\log.txt | ForEach-Object { # Match timestamp including AM/PM, handle 1-2 digit months/days/hours $timeMatch = [regex]::match($_, '^[0-9]{1,2}/[0-9]{1,2}/[0-9]{4} [0-9]{1,2}:[0-9]{2}:[0-9]{2} (AM|PM)') if ($timeMatch.Success -and [datetime]$timeMatch.Value -gt (Get-Date).AddDays(-90)) { $_ } } | Set-Content .\purgedlogfile.txt
Key Changes:
[0-9]{1,2}for month/day/hour: matches both single-digit (like9/1) and double-digit (like10/05) values- Added
(AM|PM)to capture the time period suffix - Added a check for
$timeMatch.Successto avoid errors if a line doesn't match the timestamp format
A More Reliable Alternative: Use ParseExact
Instead of relying on regex to extract the timestamp, you can directly parse the known format with [datetime]::ParseExact—this is less error-prone if your log format is consistent:
$cutoffDate = (Get-Date).AddDays(-90) $timeFormat = 'M/d/yyyy hh:mm:ss tt' # Exact format matching your logs Get-Content .\log.txt | ForEach-Object { # Extract just the timestamp part by removing everything after " - status " $timestampStr = $_ -split ' - status ' | Select-Object -First 1 try { $timestamp = [datetime]::ParseExact($timestampStr, $timeFormat, $null) if ($timestamp -gt $cutoffDate) { $_ } } catch { # Optional: Handle lines that don't match the format (e.g., log headers) Write-Warning "Skipping invalid line: $_" } } | Set-Content .\purgedlogfile.txt
This method explicitly tells PowerShell exactly what timestamp format to expect, so you don't have to tweak regex for edge cases.
内容的提问来源于stack exchange,提问作者Kyle Reyes

