I'm having the weirdest and most annoying problem with dealing with a string here that I need to convert to DateTime.
I'm doing the exact same thing from 2 different CSV files - it works perfectly on the first one, keeps returning an error on the second one.
$userDateOut = Get-Date $sourceLine.Date_OUT -Format "dd/MM/yyyy"
$userDateOut = ($userDateOut -as [datetime]).AddDays(+1)
$userDateOut = Get-Date $userDateOut -Format "dd/MM/yyyy"
In the first CSV, Date_OUT is just 31/12/2021 for example, and in the second one it's 31/12/2021 0:00:00.
So before the 3 lines to create $userDateOut, I do
$userDateOut = $sourceLine.Date_OUT.SubString(0,10)
Which makes me end up with the same type of variable as with the first CSV
PS C:\Windows\system32> $userDateOut = $sourceLine.Date_Out.Substring(0,10)
PS C:\Windows\system32> $userDateOut
31/12/2021
PS C:\Windows\system32> $userDateOut.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String System.Object
However, with this variable, I'm getting
PS C:\Windows\system32> $userDateOut = Get-Date $userDateOut -Format "dd/MM/yyyy"
Get-Date : Cannot bind parameter 'Date'. Cannot convert value "31/12/2021" to type "System.DateTime". Error: "String was not recognized as a valid DateTime."
At line:1 char:25
+ $userDateOut = Get-Date $userDateOut -Format "dd/MM/yyyy"
+ ~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-Date], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.GetDateCommand
And I don't know why... Can someone help ?