Trouble comparing created date with current date

cvandal picture cvandal · May 8, 2013 · Viewed 9.2k times · Source

Hopefully someone can give me a hand. I'm having trouble comparing the current date to the date which a file was created. The output I get from each date is below along with my code.

Created date output:

21/05/2012 10:27:25 PM

Current date output:

8/05/2013 12:00:00 AM

Is it possible to compare these dates?

My code is as follows:

$host = Read-Host 'Host: '
$username = Read-Host 'Username: '
$password = Read-Host 'Password: '

Connect-VIServer -Server $host -User $username -Password $password

$snapshotDate = Get-Snapshot -VM CONVCORPSPOINT | Select-Object Created | Format-Table -HideTableHeaders
$currentDate = Get-Date | Select-Object Date | Format-Table -HideTableHeaders

$snapshotDate
$currentDate

if ($snapshotDate -lt $currentDate) {
    Write-Host 'The snapshot date is earlier than the current date'
}
else {
    Write-Host 'The snapshot date is not earlier than the current date'
}

Answer

David Brabant picture David Brabant · May 8, 2013

Try this:

$x = Get-Date

You can get a list of all methods associated to the date object doing this:

$x | gm

You can format your date like this:

$x.ToString("yyyyMMdd hh:mm:ss")

All format options are described here. You can then normalize your dates and compare them easily.