How do I use "DO... Until" for a script date prompt

Viewed 63

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.

4 Answers

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])

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

To offer a concise alternative that relies on the fact that casting a string to [datetime] in PowerShell by default recognizes date strings such as '12/24/2022' (representing 24 December 2022), irrespective of the current culture, because PowerShell's casts, among other contexts, use the invariant culture:

$prompt = 'What is the effective date? Format: MM/DD/YYYY'

# Keep prompting until a valid date is entered.
while (-not ($startDate = try { [datetime] (Read-Host $prompt) } catch {})) {}

"Date entered: "; $startDate

Note: A [datetime] cast also recognizes other string formats, such as '2022-12-24'

Related