sk8er_boi47
sk8er_boi47

Reputation: 383

Compare Dates in loop

I have a requirement where I need to read a date from a CSV file and compare it to a date variable within the script. However, my code doesn't work when some of the date entries in the CSV file are blank. Any idea how I can store a blank date in [datetime] variable?

Here's the part of my code:

#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"

}

Above code works fine when $whenCreated contains some value, but when it's blank PowerShell obviously cannot compare a date variable with blank value :( The only solution I can see now is to check if $whenCreated is blank and save a very old date like it happens in Excel, e.g.:

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

Should this be OK or is there another logical solution?

Upvotes: 0

Views: 1321

Answers (2)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200203

Your problem most likely isn't with the comparison, but with the conversion of the blank value to a date via ParseExact(). If you want accounts with no date treated as dormant you could simply do something like this:

$whenCreated = $_.whenCreated
if ($whenCreated) {
  $whenCreated = [DateTime]::ParseExact($whenCreated, 'dd/MM/yyyy', $null)
}

if ($whenCreated -le $InactivityDate) {
  'Account is dormant'
}

Checking if an empty string (or $null) is lesser or equal to $InactivityDate will return $true as long as $InactivityDate contains a date.

Upvotes: 2

user2226112
user2226112

Reputation:

You already test if the string is empty, which is good. But there is no need to assign a fake old date, you can simply assign $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"
}

Upvotes: 0

Related Questions