specific text of today's date from txt file by powershell

前端 未结 4 639
温柔的废话
温柔的废话 2021-01-28 08:45

I have a text file. Similar to this.

This is a sample data.
This is a sample data.
This is a sample data.
Sat Jun 06 08:17:01 2015
WARNING: Cannot delete file.
E         


        
4条回答
  •  天命终不由人
    2021-01-28 09:14

    $curdate is a string with the format ddMMyyyy, whereas the string in the log file containing the date is in the format ffffd MMM dd HH:mm:ss yyyy, which I assume to be the current locale, hence your use of Get-Date -UFormat %c.

    Therefore, your if($_ -eq $curdate) statement won't work.

    if($_ -eq $cur_date1) will return true if the timestamp contained in $_ represents the exact second your script starts running, but the subsequent Where-Object statement won't evaluate to $true (since $_ is currently referring to the line with the date, not the error) and even if it did, wouldn't return anything (you haven't piped anything to Where-Object or specified an InputObject parameter argument)

    As a general rule, for date comparison, don't use a string representation, use the Date property of the datetime objects you are comparing.

    Wrong/frail approach:

    Get-ChildItem |Where-Object { $_.LastWriteTime.ToString("ddMMyyyy") -eq $datestring }
    

    Safe approach:

    $today = (Get-Date).Date
    Get-ChildItem |Where-Object { $_.LastWriteTime.Date -eq $today }
    

    If you want to extract the preceding date of an error message, the easiest way is to use Select-String with the Context parameter:

    Select-String -Path C:\samplefile.log -Pattern "^Error" -Context 2 | Select-Object -First 1
    
      C:\samplefile.log:4:Sat Jun 06 08:17:01 2015
      C:\samplefile.log:5:WARNING: Cannot delete file.
    > C:\samplefile.log:6:Error-101
      C:\samplefile.log:7:This is a sample data.
      C:\samplefile.log:8:This is a sample data.
    

    You can then use the output data from Select-String to grab and compare the date:

    $Today  = (Get-Date).Date
    $Format = 'ffffd MMM dd HH:mm:ss yyyy'
    Select-String -Path C:\samplefile.log -Pattern '^Error' -Context 2 | Where-Object {
        [DateTime]::ParseExact($_.Context.PreContext[0],$Format,$null).Date -eq $Today
    } | Select-Object @{Name="Error";Expression={$_.Line}},@{Name="Date";Expression={[DateTime]::ParseExact($_.Context.PreContext[0],$Format,$null).ToString("ddMMyyyy")}}
    

提交回复
热议问题