'How to check if a DateTime value is not null or empty?
I want to check if the DateTime field is not an empty\null string. if datetime field is not null then I will do stuff.
[DateTime]$expdate = Read-Host "Expiration Date? MM/DD/YYYY"
$newexpdate = $expdate.AddDays(1)
if (!([DateTime]$expdate -eq "")) {
Write-Host -ForegroundColor Green $($newexpdate) "Date Time entered"
}
Here is my error message:
Cannot convert value "" to type "System.DateTime". Error: "String was not recognized as a valid DateTime." At line:1 char:2 + [DateTime]$expdate = Read-Host "Expiration Date? MM/DD/YYYY" + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : MetadataError: (:) [], ArgumentTransformationMetadataException + FullyQualifiedErrorId : RuntimeException`
What can I do to check if a field is not a string but is DateTime
object?
Solution 1:[1]
Why prompt for user input when you can declare a mandatory DateTime
-type parameter to a function or script? If the parameter is missing, PowerShell will prompt the user for the date and time and the user can enter it at runtime. (If you use Read-Host
, you can't automate.)
Solution 2:[2]
There is no empty [DateTime] value, it can either be a $null or a datetime value.
Read-Host returns string type. What you're trying to do is assigning string values to a [DateTime] type which will cause error.
You can rewrite your code like this:
$expdate = Read-Host "Expiration Date? MM/DD/YYYY"
if (![string]::IsNullOrEmpty($expdate))) {
#add logic to check $expdate is valid datetime
#then you can do this
$newexpdate = ([DateTime]$expdate).AddDays(1)
Write-Host -ForegroundColor Green $($newexpdate) "Date Time entered"
}
Solution 3:[3]
Your logic doesn't make much sense, but here's what I think you're trying to do (below). To directly address your last question, you can test the type of an object by using the -is
or -isNot
operator which will return $True
\ $False
depending on the match. The other side of the operator can be a string or type accelerator, i.e. [DateTime]'10/10/2010' -is 'DateTime'
or [DateTime]'10/10/2010' -is [DateTime]
both evaluate to $True
Do
{
$ExpDate = Read-Host -Prompt 'Expiration date? MM/DD/YYYY'
} Until ($ExpDate -match '\d{1,2}\/\d{1,2}\/\d{2,4}')
$NewExpDate = ([DateTime]$ExpDate).AddDays(1)
If ($ExpDate)
{
Write-Host "$NewExpDate Date Time entered." -ForegroundColor 'Green'
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Bill_Stewart |
Solution 2 | I'm A Guest |
Solution 3 |