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

前端 未结 4 594
温柔的废话
温柔的废话 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条回答
  •  梦毁少年i
    2021-01-28 09:31

    You can try converting each line to a datetime. That's not a standard date format, however, so [datetime]::TryParse() isn't likely to work. That means you'll need to use [datetime]::TryParseExact(), which is moderately more irritating because you have to give it a provider and a style, even though you're probably not using either.

    $dateString = 'Sat Jun 06 08:17:01 2015';
    
    [System.Globalization.CultureInfo]$provider = [System.Globalization.CultureInfo]::InvariantCulture;
    [System.Globalization.DateTimeStyles]$style = [System.Globalization.DateTimeStyles]::None;
    
    $format = "ffffd MMM dd HH:mm:ss yyyy";
    [ref]$parsedDate = get-date;
    [DateTime]::TryParseExact($dateString, $format, $provider, $style, $parsedDate);
    $parsedDate.Value;
    

    A key thing to note is that both TryParse() and TryParseExact() don't return values; they return True when the parsing is successful, and False when it fails. In order to pass the result, you pass a variable by reference and the function modifies the referenced variable. $parsedDate.Value is where the actual datetime value is because $parsedDate itself is a reference (pointer).

    If the function fails and returns false, $parsedDate will have a value of [datetime]::MinValue (Jan 1, 0001).

提交回复
热议问题