How do I check that a string contains a date?

You can let the .NET Framework help you with this:

function ParseDate([string]$date)
{
    $result = 0
    if (!([DateTime]::TryParse($date, [ref]$result)))
    {
        throw "You entered an invalid date: $date"
     }

    $result
}

ParseDate 'June 51, 2001'

Yes, you can check that a string contains date by using ‘(-as [DateTime])’. The problem in my original script is that I assumed that script input parameters are strings. Apparently, numerical parameter is automatically converted to integer, unless it is typed with quotes. So, I should have written

if ([string]$date -as [DateTime])  

forcing converting possible number back to string, as Keith does in his answer.

Same flaw applies to my integer check. The script fails when given “Oct,3” (without quotes). Does PS create an array here?

Why does parsing fail when check succeeds? Johannes explained that. Expression

$date -as [DateTime]

instructs PS to convert input to date. Converting number makes sense (date 1 is January 01, 0001), so it does not fail when given a number. Expression

[DateTime]::Parse($date)

specifically parses a string, so giving it an integer does not make sense and leads to error.

It was wasteful of me to use both, anyway. First, I convert to date in the condition, only to throw away the result. Then, I recreate the result with different syntax. I’m changing that to

$date = $date -as [DateTime];
if (!$date)
{  
    'You entered an invalid date'
    exit 1
}

Thanks all.

Tags:

Powershell