【问题标题】:Compare Dates in loop比较循环中的日期
【发布时间】:2023-03-14 21:47:01
【问题描述】:

我有一个要求,我需要从 CSV 文件中读取日期并将其与脚本中的日期变量进行比较。但是,当 CSV 文件中的某些日期条目为空白时,我的代码不起作用。知道如何在 [datetime] 变量中存储空白日期吗?

这是我的代码的一部分:

#This is my date variable in script
$InactivityDate = (Get-Date).AddDays(-62).Date


Import-Csv $MyCSV | ForEach {

#This is the date variable i'm reading from csv file
$whenCreated = $_.whenCreated


#This converts value in string variable $whenCreated to [DateTime] format
$ConvertWhenCreated = ([datetime]::ParseExact($whenCreated,"dd/MM/yyyy",$null))

#Comparing dates
if($ConvertWhenCreated -le $InactivityDate)
{

"Account is dormant"

}

$whenCreated 包含一些值时,上面的代码可以正常工作,但是当它为空白时,PowerShell 显然无法将日期变量与空白值进行比较:( 我现在能看到的唯一解决方案是检查 $whenCreated 是否为空白并保存一个非常旧的日期,就像它在 Excel 中发生的那样,例如:

if($whenCreated -eq "")
{
$whenCreated = "01/01/1900 00:00:00"
}

这应该没问题还是有其他合乎逻辑的解决方案?

【问题讨论】:

    标签: date powershell


    【解决方案1】:

    您的问题很可能不在于比较,而在于通过ParseExact() 将空白值转换为日期。如果您希望将没有日期的帐户视为休眠帐户,您可以简单地执行以下操作:

    $whenCreated = $_.whenCreated
    if ($whenCreated) {
      $whenCreated = [DateTime]::ParseExact($whenCreated, 'dd/MM/yyyy', $null)
    }
    
    if ($whenCreated -le $InactivityDate) {
      'Account is dormant'
    }
    

    只要$InactivityDate 包含日期,检查空字符串(或$null)是否小于或等于$InactivityDate 将返回$true

    【讨论】:

      【解决方案2】:

      您已经测试了字符串是否为空,这很好。但是没有必要分配一个假的旧日期,您可以简单地分配 $null:

      $InactivityDate = (Get-Date).AddDays(-62)
      
      $dateString = "2014-11-01"
      
      if ($dateString) {
          $date = Get-Date $dateString
      } else {
          $date = $null
      }
      
      if ($date -le $InactivityDate) {
          "Account is dormant"
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-12
        • 1970-01-01
        • 2017-04-28
        • 1970-01-01
        相关资源
        最近更新 更多