Converti la stringa in DateTime in Powershell da CSV
Sto avendo il problema più strano e fastidioso di gestire una stringa qui che devo convertire in DateTime.
Sto facendo la stessa identica cosa da 2 diversi file CSV: funziona perfettamente sul primo, continua a restituire un errore sul secondo.
$userDateOut = Get-Date $sourceLine.Date_OUT -Format "dd/MM/yyyy"
$userDateOut = ($userDateOut -as [datetime]).AddDays(+1)
$userDateOut = Get-Date $userDateOut -Format "dd/MM/yyyy"
Nel primo CSV, Date_OUT è solo 31/12/2021per esempio, e nel secondo è 31/12/2021 0:00:00.
Quindi, prima delle 3 linee da creare $userDateOut, lo faccio
$userDateOut = $sourceLine.Date_OUT.SubString(0,10)
Il che mi fa finire con lo stesso tipo di variabile del primo 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
Tuttavia, con questa variabile, ottengo
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
E non so perché ... Qualcuno può aiutare?
Risposte
-Formatsi converte semplicemente [datetime]in a [string]- non influenza in alcun modo l' analisi delle stringhe di input .
Per questo, hai bisogno di [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)
È quindi possibile utilizzare Get-Date -Formatper riconvertirlo in un formato di output previsto, se necessario: