My script’s input parameter is a date or a number. Here’s a script that works fine, so you can see what I am trying to do:
param($date = (Get-Date))
if ($date -match "^\d+$")
{
$date = (Get-Date).AddDays($date)
}
elseif ($date -as [DateTime])
{
$date = [DateTime]::Parse($date)
}
else
{
'You entered an invalid date'
exit 1
}
Here’s my previous attempt that does not work:
param($date = (Get-Date))
if ($date -as [DateTime])
{
$date = [DateTime]::Parse($date)
}
elseif ($date -match "^\d+$")
{
$date = (Get-Date).AddDays($date)
}
else
{
'You entered an invalid date'
exit 1
}
When I input a number, the script breaks at date parsing line. It looks like my “is is date” check returns true when given a number.
Is it a bug? Is it by design?
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
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
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
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
Thanks all.