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
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).