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

前端 未结 4 601
温柔的废话
温柔的废话 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:28

    I got pinged to the question, so here's my take on a solution:

    #Create test file from posted data:
    (@'
    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.
    Error-101
    Error-100
    Error-102
    This is a sample data.
    This is a sample data.
    Error-10666
    This is a sample data.
    Sat Jun 06 10:17:01 2015
    File deleted.
    This is a sample data.
    This is a sample data.
    Sat Jun 06 10:17:01 2015
    File deleted.
    Sat Jun 06 11:17:01 2015
    WARNING: Cannot delete file.
    Error-101
    This is a sample data.
    Sat Jun 06 18:17:01 2015
    WARNING: Cannot delete file.
    Error-101
    This is a sample data.
    '@).split("`n") |
    #where { -notmatch '^#'} |
    foreach {$_.trim()} |sc testfile.txt
    
    #Proxy function for testing
    function get-date {[datetime]'06/06/2015 18:17:01'} 
    
    #Actual solution code follows:
    
    $DateSearch = (get-date).ToString('MMM dd [0-9:]+ yyyy(.+)')
    $DateSearch = '(?ms)' + $DateSearch
    
    if ((Get-Content testfile.txt -Raw) -match  $DateSearch)
    { $Matches[1].Split("`n") -like 'Error*' }
    
    #remove the proxy function:
     remove-item function:get-date
    
    Error-101
    Error-100
    Error-102
    Error-10666
    Error-101
    Error-101
    

    This uses the [datetime] tostring() method to help create a regex to search for today's date in the file. Then it captures everything from that point to the end of the file, splits it at the newlines and filters out everything except the Error records.

    Ignore that proxy function for get-date. That's just there to get the script to work with the test data.

提交回复
热议问题