Question

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'
}
Was it helpful?

Solution

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.

OTHER TIPS

A common solution is to compare against the date part only (not including the time parts). You can do that by comparing the Date property (which sets the time to midnight):

$date.Date

Or by explicitly comparing against the short ate string :

$date.ToShortDateString()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top