CSV'den Powershell'de dizeyi DateTime'a dönüştürün

Sep 12 2020

Burada DateTime'a dönüştürmem gereken bir dizeyle uğraşmakla ilgili en tuhaf ve en sinir bozucu sorunu yaşıyorum.

Tam olarak aynı şeyi 2 farklı CSV dosyasından yapıyorum - ilkinde mükemmel çalışıyor, ikincisinde bir hata döndürmeye devam ediyor.

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

İlk CSV'de Date_OUT 31/12/2021örneğin, ikincisinde ise 31/12/2021 0:00:00.

Yani 3 satır oluşturmak için önce $userDateOut, yapmak

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

Bu da beni ilk CSV ile aynı türde değişkenle sonuçlandırıyor

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

Ancak bu değişkenle,

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

Ve neden bilmiyorum ... Biri yardım edebilir mi?

Yanıtlar

3 MathiasR.Jessen Sep 11 2020 at 22:45

-FormatSadece dönüştürür [datetime]bir etmek [string]- bu giriş dizeleri ayrıştırma etkilemez herhangi bir şekilde.

Bunun için ihtiyacınız olan [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)

Daha sonra, Get-Date -Formatgerekirse onu tekrar amaçlanan çıktı biçimine dönüştürmek için kullanabilirsiniz :