Konwertuj ciąg na DateTime w programie PowerShell z pliku CSV
Mam najdziwniejszy i najbardziej irytujący problem z obsługą ciągu znaków, który muszę przekonwertować na DateTime.
Robię dokładnie to samo z 2 różnymi plikami CSV - działa doskonale na pierwszym, ciągle zwraca błąd na drugim.
$userDateOut = Get-Date $sourceLine.Date_OUT -Format "dd/MM/yyyy"
$userDateOut = ($userDateOut -as [datetime]).AddDays(+1)
$userDateOut = Get-Date $userDateOut -Format "dd/MM/yyyy"
W pierwszym CSV 31/12/2021na przykład Date_OUT , aw drugim to 31/12/2021 0:00:00.
Więc przed utworzeniem 3 linii $userDateOut, robię
$userDateOut = $sourceLine.Date_OUT.SubString(0,10)
Co sprawia, że otrzymuję taki sam typ zmiennej, jak w przypadku pierwszego pliku 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
Jednak z tą zmienną otrzymuję
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
I nie wiem dlaczego ... Czy ktoś może pomóc?
Odpowiedzi
-Formatpo prostu konwertuje [datetime]na a [string]- w żaden sposób nie wpływa na parsowanie ciągów wejściowych .
W tym celu potrzebujesz [datetime]::ParseExact():
$dateString = '31/12/2021' # You can pass multiple accepted formats to ParseExact, this should cover both CSV files $inputFormats = @(
'dd/MM/yyyy H:mm:ss'
'dd/MM/yyyy'
)
$parsedDatetime = [datetime]::ParseExact($dateString, $inputFormat, $null)
W Get-Date -Formatrazie potrzeby możesz użyć go do konwersji z powrotem do zamierzonego formatu wyjściowego: