Get-Date小于文本文件中的日期/字符串

时间:2018-04-23 12:13:14

标签: powershell

我编写了一些代码,用于将有关网站许可的保修信息解析为.txt文件。我的目标(和问题)是将.txt文件的保修到期日与当前日期进行比较,以了解保修是否已过期。

我是一个PowerShell初学者,所以我的代码可能不太合乎逻辑,但这是我到目前为止所做的:

#the Invoke-WebRequest is up here which outputs into $output_file

#files
$output_file = ‘c:\warrantyinfo.txt’
$warranty_file = 'c:\warrantydate.txt'

#At this point all the warranty information is in $output_file
#With the code below I do a select string to get the information I want and 
#get rid of everything else
$warrantyUntil = Get-Content $output_file
$warrantyUntil | Select-String '("toCustomerDate":)["]\d{4}\-(0?[1- 
9]|1[012])\-(0?[1-9]|[12][0-9]|3[01])*' -AllMatches | Foreach-Object 
{$_.Matches} | Select value > $warranty_file

#I now have "toCustomerDate":"yyyy-mm-dd in a new .txt file 
#Below I try to grab just the date in the format yyyy-mm-dd in order to 
#compare with todays date. I think this is where I go wrong.
$warrantyDate=Select-String -Path $warranty_file -Pattern "\d{4}\-(0?[1- 
9]|1[012])\-(0?[1-9]|[12][0-9]|3[01])*" -AllMatches | Foreach-Object 
{$_.Matches} | Select value

#Current date in the format I want
$currentDate=Get-Date -UFormat "%Y-%m-%d"

#Compare warrantyDate and currentDate to decide if warranty has expired or 
#not
if ($currentDate -lt $warrantyDate) {
Write-Host "Warranty is valid"
} else {
Write-Host "Warranty has expired"
}

2 个答案:

答案 0 :(得分:1)

由于数据类型不匹配,会发生这种情况。

首先,您的$currentDate是字符串类型,而您可能希望它是datetime类型,这是因为执行了特定的格式化而发生的。 $warrantyDate也是字符串甚至是字符串数组。你也需要考虑到这一点。

您可能希望通过在变量名之前放置适当的类加速来明确设置初始化变量的数据类型。像这样:

[DateTime]$currentDate=Get-Date -UFormat "%Y-%m-%d"
[DateTime]$warrantyDate=Select-String -Path $warranty_file -Pattern "\d{4}\-(0?[1- 
9]|1[012])\-(0?[1-9]|[12][0-9]|3[01])*" -AllMatches | Foreach-Object 
{$_.Matches} | Select value

要查看变量类型是什么,请使用:

$currentDate.GetType().Name

答案 1 :(得分:0)

使用文件warrantyinfo.txt

"toCustomerDate":"2018-04-22"
"toCustomerDate":"2018-04-24"

和这个脚本:

$currentDate=Get-Date

$output_file = ‘.\warrantyinfo.txt’

$warrantyUntil = Get-Content $output_file | 
  Select-String '(?<="toCustomerDate":)"\d{4}\-(0?[1-9]|1[012])\-(0?[1-9]|[12][0-9]|3[01])"' -AllMatches

$warrantyUntil
$warrantyUntil.matches.value

$warrantyUntil.matches.value | ForEach {
    if ($currentDate -lt [datetime]$_.trim('"')) {
        Write-Host "Warranty $_ is valid"
    } else {
        Write-Host "Warranty $_ has expired"
    }
}

您将获得此示例输出:

"toCustomerDate":"2018-04-22"
"toCustomerDate":"2018-04-24"
"2018-04-22"
"2018-04-24"
Warranty "2018-04-22" has expired
Warranty "2018-04-24" is valid

该脚本使用不同的RegEx,(?<="toCustomerDate":)pom.xml,不属于匹配值。