CSV에서 Powershell의 문자열을 DateTime으로 변환

Sep 12 2020

DateTime으로 변환해야하는 여기에서 문자열을 처리하는 데 가장 이상하고 성가신 문제가 있습니다.

두 개의 서로 다른 CSV 파일에서 똑같은 작업을 수행하고 있습니다. 첫 번째 파일에서는 완벽하게 작동하고 두 번째 파일에서는 계속 오류를 반환합니다.

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

첫 번째 CSV에서 Date_OUT은 31/12/2021예를 들어, 두 번째 CSV에서는 31/12/2021 0:00:00.

그래서 3 선 작성하기 전에 $userDateOut, 내가 할

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

첫 번째 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

그러나이 변수를 사용하면

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

왜 그런지 모르겠네요 ... 누군가 도와 줄 수 있나요?

답변

3 MathiasR.Jessen Sep 11 2020 at 22:45

-Format그냥 a로 변환 [datetime]합니다 [string]- 어떤 식 으로든 입력 문자열의 구문 분석에 영향을주지 않습니다 .

이를 위해서는 [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)

그런 다음 Get-Date -Format필요한 경우를 사용하여 의도 한 출력 형식으로 다시 변환 할 수 있습니다 .