Idera nSoftware Compellent

Converting User Input to Date

PowerShell uses the US/English date format when converting user input to DateTime, which can cause unexpected results if using a different culture. For example, on German systems "1.3.2000" resolves to March 1, 2000. PowerShell can convert this input to January 3, 2000.

To convert DateTime values based on your current culture, use the DateTime's parse() method:

[DateTime]::Parse('1.3.2000')

But what if the user enters nonsense that cannot be converted to a date? You get an exception!

There are two workarounds. First, you can start using -as to see if the user input can be converted to a DateTime at all. If so, use parse() to get the culture-specific date:

$date = Read-Host 'Enter your birthday'
if (($date -as [DateTime]) -ne $null) {
$date = [DateTime]::Parse($date)
$date
} else {
'You did not enter a valid date!'
}

Secondly, you can use an error handler to catch the exception like so:

$date = Read-Host 'Enter your birthday'
trap {'You did not enter a valid date!'; continue}
. {
$date = [DateTime]::Parse($date)
$date
}

Posted Dec 31 2008, 08:00 AM by ps1

Comments

The Energized Tech wrote Listing Installed Applications Revisted
on 10-09-2009 5:36 AM

I noticed in the Powershell forums somebody looking for a Script to show what date some Sql updates went in. I don't think this new one met the need but I started wondering If I could dump a little more than the installed programs. Turns out the Registry

Copyright 2010 PowerShell.com. All rights reserved.