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

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

    While you parse error*.txt file, you can save last seen date in a variable. So, when you encounter Error-* record, you will know to what date it related to.

    $Today=[datetime]::Today
    Get-Content D:\Script\system.txt|
    ForEach-Object {
        $System=$_
        Get-ChildItem -Path "filesystem::\\$System\D$\Error" -Filter error*.txt|
        # filesystem:: allows code to work, even if current provider is not a filesystem provider.
        Where-Object {$_.LastWriteTime.Date-eq$Today}|
        ForEach-Object {
            Get-Content -LiteralPath $_.PSPath|
            ForEach-Object {
                $ParseDate=New-Object datetime
                $LastSeenDate=$null
            } {
                if([datetime]::TryParseExact($_,'ffffd MMM dd HH:mm:ss yyyy',[cultureinfo]::InvariantCulture,'None',[ref]$ParseDate)){
                    $LastSeenDate=$ParseDate
                }
                if($_.StartsWith('Error-')){
                    [PSCustomObject]@{
                        Error=$_
                        Date=$LastSeenDate
                        System=$System
                    }
                }
            }
        }
    }|
    Where-Object {$_.Date.Date-eq$Today}
    

提交回复
热议问题