1

In PowerShell, I am trying to convert a string that I selected from a text file to a date so I can add or substract days, hours and so on from it. The problem is that when I try to convert the resulted string from the text file, I receive the following error:

Exception calling "ParseExact" with "3" argument(s): "String was not recognized as a valid DateTime."

At line:15 char:5

+     [datetime]::ParseExact($SC4,'HH:mm:ss', $null)
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : FormatException

The Code:

Get-Content results2.txt | ForEach-Object{
$splitUp = $_ -split " "
$SC=$splitUp[0] -split " "
$SC2=$splitUp[1] -split " "
$SC3=$SC + $SC2
Write-Host -NoNewline $SC3 | Write-Output $SC4
Write-Host $SC4
$r=[datetime]::ParseExact($SC4,'dd/MM/yyyy HH:mm:ss', $null)
echo $r

}

The file result2.txt, from which I read, contains the following:

09/07/2017 16:35:56 - 2017-09-07 14:55:51,312 [342]
09/07/2017 16:35:56 - 2017-09-07 14:55:51,312 [342]
09/07/2017 16:35:56 - 2017-09-07 14:56:54,918 [305]
09/07/2017 16:35:56 - 2017-09-07 14:58:36,133 [113]

2 Answers 2

1

The problem is because $SC4 is an empty variable. Your attempt to populate it via a pipe of output from Write-Host doesn't work (because Write-Host writes to the console and not to the pipeline).

That whole part over complicates things and can just be removed. This works fine in my testing:

Get-Content result2.txt | ForEach-Object {
    $splitUp = $_ -split " "
    $SC=$splitUp[0] -split " "
    $SC2=$splitUp[1] -split " "
    $SC3 = $SC + $SC2
    $r=[datetime]::ParseExact($SC3,'dd/MM/yyyy HH:mm:ss', $null)
    echo $r
}

Here's a shorter solution that uses regex to match the first date in the file:

Get-Content result2.txt | ForEach-Object {
    $Check = $_ -Match '^\d{2}/\d{2}/\d{4} \d{2}:\d{2}:\d{2}(?= .*$)'
    If ($Check) { $R=[datetime]::ParseExact($Matches[0],'dd/MM/yyyy HH:mm:ss', $null) }
    Echo $R
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Now it works. I did that because if I display $SC3 it shows the date on one row and time on the next one so I thought it will interfere with the format required by ParseExact. Thanks again!
0

Other method:

Get-Content "c:\temp\test.txt" | ForEach-Object {
    [datetime]::ParseExact(($_ -split " - ")[0],'dd/MM/yyyy HH:mm:ss', $null)
}


#short version
gc "c:\temp\test.txt" |%{[datetime]::ParseExact(($_ -split " - ")[0],'dd/MM/yyyy HH:mm:ss', $null)}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.