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?
TryParseExact("15:30:20", "yyyy-MM-dd HH:mm:ss",CultureInfo.
There are two possible solutions: Use a SimpleDateFormat and try to convert the String to Date . If no ParseException is thrown the format is correct. Use a regular expression to parse the String.
TryParse() function to check if a particular string is a valid datetime not depending on any cultures. To my surprise , the function returns true for even strings like "1-1", "1/1" . etc.
This is a short alternative:
function isDate([string]$strdate)
{
[boolean]($strdate -as [DateTime])
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With