Reputation: 3
I'm running into an issue with converting user input into a DateTime
type while returning it in a specific format. I've been searching for a few hours now and everything I've tried so far hasn't worked.
When I enter the date, I want it to stay as the format I entered it in so that Get-MessageTrace
can read it.
What I'm looking for is to enter "1/23/2019" and ParseExact
would shoot it back out as "1/23/2019".
What I'm getting is $NewDate1
being "Wednesday, January 23, 2019 12:01:00 AM"
I'm probably not doing this right or maybe doing something wrong, but I could use some help, please.
$UserEmail = Read-Host -Prompt 'Enter your WT email address'
$Date1 = Read-Host -Prompt 'Enter the first date (MM/DD/YYYY)'
$Date2 = (Read-Host -Prompt 'Enter the second date (MM/DD/YYYY)'
$NewDate1 = [datetime]::parseexact($Date1, 'm/d/yyyy', $null)
$NewDate2 = [datetime]::parseexact($Date2, 'm/d/yyyy', $null)
Get-MessageTrace -RecipientAddress 'UserEmail' -StartDate '$NewDate1'
-EndDate 'NewDate2'
Error I receive:
Cannot process argument transformation on parameter 'StartDate'. Cannot convert value "$NewDate1" to type "System.DateTime". Error: "String was not recognized as a valid DateTime." + CategoryInfo : InvalidData: (:) [Get-MessageTrace], ParameterBindin...mationException + FullyQualifiedErrorId : ParameterArgumentTransformationError,Get-MessageTrace + PSComputerName : outlook.office365.com
Upvotes: 0
Views: 939
Reputation: 7029
First, regarding date string formatting, a lower case 'm' represents minutes and an uppercase 'M' represents months. That is why '1/23/2019' is being interpreted as Wednesday, January 23, 2019 12:01:00 AM (emphasis on first minute of the day). The pattern you likely want is 'M/d/yyyy'.
Second, I'm not entirely sure you understand date parsing. ParseExact
does not take a string and "shoot it back" as a date with a specific string representation. ParseExact
will convert a string formatted as a date into a DateTime
object. That DateTime
object does not have an inherent format or string representation (unless you consider ToString()
to be the canonical date format), it's just a date. If, at a later time, you need a string representation of that date you will have to convert it to a string.
Third, you are passing a string with the value of "$NewDate1" to -StartDate
, hence the exception stating:
Cannot convert value "$NewDate1" to type "System.DateTime"
Remove the single quotes around '$NewDate1' to pass the value of the variable rather than the name of the variable.
Upvotes: 1