You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PowerShell中解析含AM/PM的时间戳文本行并过滤?

Solution for Filtering Log Lines with AM/PM Timestamps in PowerShell

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 (like 9/1) and double-digit (like 10/05) values
  • Added (AM|PM) to capture the time period suffix
  • Added a check for $timeMatch.Success to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:09:36