I am trying to use "DO...Until" in a script to require a user to enter a date. I want to ensure that the date is valid and that the script is able to use that date. I'm fairly new to PS and I'm not certain what I'm doing wrong. It keeps looping even if I put in a valid date.
Do #Start Get Effective Date#
{
$StartDate = Read-Host ' What is the effective date? Format: MM/DD/YYYY '
if ($StartDate -ge 1)
{ Write-Host " You Entered an Effective date of: $StartDate "
}
else
{ Write-Host " Please enter the effective date " -ForegroundColor:Green }
} Until ($StartDate -ge 1)
#End Get Effective Date#
I'm not certain if I am using the wrong '-ge' or not. Once I am able to get a valid date from the user I want the script to move to the next step.
CodePudding user response:
you were close to ;-)
Do{
[string]$StartDate = Read-Host 'What is the effective date? Format: MM/DD/YYYY'
try {
[datetime]$StartDate = [datetime]::ParseExact($startdate, 'MM/dd/yyyy', [cultureinfo]::InvariantCulture)
}
Catch {
}
}
Until ($StartDate -is [DateTime])
CodePudding user response:
The TryParseExact
method seems a good fit for what you're looking to achieve, no need for error handling:
[ref] $date = [datetime]::new(0)
do {
$startdate = Read-Host 'What is the effective date? Format: MM/DD/YYYY'
$parsed = [datetime]::TryParseExact($startdate, 'MM/dd/yyyy', [cultureinfo]::InvariantCulture, [Globalization.DateTimeStyles]::None, $date)
} until($parsed)
$date.Value