Reputation: 9
I am have string which contain date and I want to compare that all last 15 days date with the date in string.
I have stored all 15 days date in array and comparing with the date in string.
#last 15 days date.
$Q = @()
$Q = for ($i=15; $i -gt 1; $i--) {
$date=Get-Date -DisplayHint Date #-Format "dd MMM yyyy"
$final=$date.AddDays(-$i)
$final.tostring("dd MMM yyyy")
}
# $array.'Description' have string like this "Enabled AD ID as per Call id: 509112 29 Oct 2019"
#comparing
if($array.'Description' -notcontains $Q){
Write-host ("true")
}else
{
write-host ("false")
}
I want comparing result.
Upvotes: 0
Views: 154
Reputation: 61068
I think you should always compare dates to dates, not their string representation unless it is in Sortable format.
Below code takes the date string from the Description attribute and converts it to a local DateTime object to compare against:
$refDate = (Get-Date).AddDays(-15).Date # midnight 15 days ago
$array | ForEach-Object {
# parse a date object from the Description string
$dateString = ([regex]'(\d{1,2} \w{3} \d{4})$').Match($_.Description).Groups[1].Value
$date = [datetime]::ParseExact($dateString, 'd MMM yyyy', [cultureinfo]"en-US")
# make it a Local date
$date = [datetime]::SpecifyKind($date, 'Local')
if ($date -gt $refDate) {
# the description date is inside the last 15 days
Write-Host "True"
}
else { Write-Host "False" }
}
As per Esperanto57's comment, in case the Description string does not contain a date to parse, below uses a try{..} catch{..}
block to tackle that:
$array | ForEach-Object {
try {
# parse a date object from the Description string
$dateString = ([regex]'(\d{1,2} \w{3} \d{4})$').Match($_.Description).Groups[1].Value
$date = [datetime]::ParseExact($dateString, 'd MMM yyyy', [cultureinfo]"en-US")
# make it a Local date
$date = [datetime]::SpecifyKind($date, 'Local')
if ($date -gt $refDate) {
# the description date is inside the last 15 days
Write-Host "True"
}
else { Write-Host "False" }
}
catch {
Write-Host "False. (The Description attribute does not contain a date.)"
}
}
Upvotes: 1
Reputation: 378
You can split $array.'Description'
, then join the last three elements and then compare it with $Q.
($($array.'Description').Split(" ") | Select-Object -Last 3) -join " "
The comparison would look something like:
if ((($($array.'Description').Split(" ") | Select-Object -Last 3) -join " ") -notcontains $Q){
Write-host ("true")
}else
{
write-host ("false")
}
Upvotes: 2