Chuyển đổi chuỗi thành DateTime trong Powershell từ CSV
Tôi đang gặp vấn đề kỳ lạ và khó chịu nhất khi xử lý một chuỗi ở đây mà tôi cần chuyển đổi sang DateTime.
Tôi đang thực hiện điều tương tự từ 2 tệp CSV khác nhau - nó hoạt động hoàn hảo trên tệp đầu tiên, tiếp tục trả về lỗi trên tệp thứ hai.
$userDateOut = Get-Date $sourceLine.Date_OUT -Format "dd/MM/yyyy"
$userDateOut = ($userDateOut -as [datetime]).AddDays(+1)
$userDateOut = Get-Date $userDateOut -Format "dd/MM/yyyy"
Trong CSV đầu tiên, Date_OUT chỉ là 31/12/2021ví dụ, và trong CSV thứ hai là 31/12/2021 0:00:00.
Vì vậy, trước 3 dòng để tạo $userDateOut, tôi làm
$userDateOut = $sourceLine.Date_OUT.SubString(0,10)
Điều này khiến tôi kết thúc với cùng một loại biến như với CSV đầu tiên
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
Tuy nhiên, với biến này, tôi nhận được
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
Và tôi không biết tại sao ... Ai đó có thể giúp đỡ?
Trả lời
-Formatchỉ chuyển đổi [datetime]thành a [string]- nó không ảnh hưởng đến việc phân tích các chuỗi đầu vào theo bất kỳ cách nào.
Để làm được điều đó, bạn cần [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)
Sau đó, bạn có thể sử dụng Get-Date -Formatđể chuyển đổi nó trở lại định dạng đầu ra dự định nếu cần: