0
votes

I am trying to use PowerShell to get the dates from a Sharepoint list and compare today's date to see if there is a match.

I have some code so far but it doesn't seem to be working. I am guessing I have some data types wrong when I am doing a comparison or something of that nature. This is the code I have so far below:

$unusableDatesArray is set with a CAML query to a list in SharePoint The column name of the date field in SharePoint is called 'UnusableDate' and of type date/time

$todaysDate = Get-Date
$foundUnusableDate = $false
ForEach($item in $unusableDatesArray) {
    if($item['UnusableDate'] -eq $todaysDate) {
        $foundUnusableDate = $true
    }
}

Even though both values appear to have 8/10/2017 12:00:00 AM as the value when I find a matching date, $foundUnusableDate never ends up being true. If anyone knows what I am doing wrong please chime in.

2
You may have to cast your date from the list into a datetime object. [Datetime]$item['UnusableDate']Jason Snell
yes that was part of my issue also, thank you.Tim Mattheson

2 Answers

0
votes

-eq is a "hard" comparison operator to get a $true out of it, both variables would need to be at the exact same datetime. This would return $true:

$date1 = [datetime]'8/11/2017 12:00:00'
$date2 = [datetime]'8/11/2017 12:00:00'

if ($date1 -eq $date2) {$true
} else {$false}

while a simple difference of one second would cause it to return $false

$date1 = [datetime]'8/11/2017 12:00:00'
$date2 = [datetime]'8/11/2017 12:00:01'
if ($date1 -eq $date2) {$true} else {$false}

To work around that you can use different approaches

$date1 = [datetime]'8/11/2017 12:00:00'
$date2 = Get-Date
if (('{0:yyyyMMdd}' -f $date1) -eq ('{0:yyyyMMdd}' -f $date2)) {$true} else {$false}

if ($date1.Date -eq $date2.Date) {$true
} else {$false}
$date1 = ([datetime]'8/11/2017 12:00:00').Date
$date2 = (Get-Date).Date
if ($date1 -eq $date2) {$true} else {$false}
0
votes
$dateToCheck = Get-Date
ForEach($item in $unusableDatesArray) {
    [DateTime]$sharePointDate = $item['UnusableDate']
        if(Get-Date $sharePointDate -Format 'MM/dd/yyyy') -eq (Get-Date $dateToCheck -Format 'MM/dd/yyyy')) {
            $foundUnusableDate = true
        }
}

The above is my final solution