powershell - 从CSV将字符串转换为Powershell中的DateTime

标签 powershell

在处理需要转换为DateTime的字符串时,我遇到了最奇怪,最烦人的问题。
我正在从2个不同的CSV文件中执行完全相同的操作-它在第一个CSV文件中工作完美,在第二个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
因此,在创建$userDateOut的3行之前,我做了
$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
而且我不知道为什么...有人可以帮忙吗?

最佳答案

-Format只是将[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将其转换回预期的输出格式:

关于powershell - 从CSV将字符串转换为Powershell中的DateTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63850203/

相关文章:

windows - 如何在 Windows 的 Powershell 中获取 Dropbox 文件夹

iis - IIS在Powershell中启用HTTP保持事件状态

使用 PowerShell 进行 MySQL 转储

file - 获取$ webclient.downloadstring以在Powershell中写入文本文件

powershell - 在Get-ADComputer中排序

string - 用于存储字符串的 PowerShell 数组

powershell - 安装 posh-git 时遇到问题

PowerShell - 如何计算参数数量

powershell - 从文件加载 PowerShell 哈希表?

powershell - 无法通过 VirtualBox 中的 PowerShell 脚本运行 Vagrant 命令