Mark Minasi's Tech Forum
Sign up Calendar Latest Topics

  Author   Comment  

Senior Member
Posts: 109
Reply with quote  #1 

I want request data from the user and check to see if it is not in the correct format then, keep prompting.  Also, if the data is not in the write format include an error message.

At first I tried this:

$inputDate = Read-Host -Prompt "Enter  Date for new account [yyyy-mm-dd]"
while (!$inputDate) {
Write-Host "ERROR: End Date is Required." -ForegroundColor $defaultInputRequiredColor
$inputDate = Read-Host -Prompt "Date for new account" }

 The problem with this it does not check to see if the data is in the right format.

Then I saw came up with this:

do {$inputDate = Read-host "Enter Date for new account [yyyy-mm-dd]"}
while ($inputDate -notmatch '\d\d\d\d-\d\d-\d\d')

The code above does get repeating until date is in the correct format.  I'm just trying to figure out where I would put an error message if the date is not in the correct format. 



Avatar / Picture

Senior Member
Posts: 421
Reply with quote  #2 
Well, you could do something along the lines of

$date = $null
while (!($date = (Read-Host "Enter date") -as [datetime])) {
    Write-Warning "Date entered is not correct or at least not in the current culture"

It is, however, my firm belief that if you're writing a script that expects user input, you should put it into parameters and check the validity of the entered data before the actual execution ( ). This way you can a. call the script in bulk if need be, and b. avoid logic errors resulting from having done stuff before the user goofs up and enters wrong information in a later step.

Evgenij Smirnov

My personal blog (German):
My stuff on PSGallery:
Previous Topic | Next Topic

Quick Navigation:

Easily create a Forum Website with Website Toolbox.