Converter string para DateTime no Powershell de CSV

Sep 12 2020

Estou tendo o problema mais estranho e irritante em lidar com uma string que preciso converter para DateTime.

Estou fazendo exatamente a mesma coisa com 2 arquivos CSV diferentes - funciona perfeitamente no primeiro, mas continua retornando um erro no segundo.

$userDateOut = Get-Date $sourceLine.Date_OUT -Format "dd/MM/yyyy"
$userDateOut = ($userDateOut -as [datetime]).AddDays(+1)
$userDateOut = Get-Date $userDateOut -Format "dd/MM/yyyy"

No primeiro CSV, Date_OUT é apenas 31/12/2021por exemplo, e no segundo é 31/12/2021 0:00:00.

Então, antes das 3 linhas para criar $userDateOut, eu faço

$userDateOut = $sourceLine.Date_OUT.SubString(0,10)

O que me faz acabar com o mesmo tipo de variável do primeiro 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

No entanto, com esta variável, estou conseguindo

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 não sei porque ... Alguém pode ajudar?

Respostas

3 MathiasR.Jessen Sep 11 2020 at 22:45

-Formatapenas converte [datetime]para um [string]- não influencia a análise de strings de entrada de forma alguma .

Para isso, você precisa [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)

Você pode então usar Get-Date -Formatpara convertê-lo de volta em um formato de saída pretendido, se necessário: