Mark Minasi's Tech Forum
Sign up Calendar Latest Topics
 
 
 


Reply
  Author   Comment  
meloao

New Friend (or an Old Friend who Built a New Account)
Registered:
Posts: 95
Reply with quote  #1 
Hi,

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. 




 

0
cj_berlin

Avatar / Picture

Senior Member
Registered:
Posts: 376
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"
}
$date


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 ( https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_functions_advanced_parameters?view=powershell-6 ). 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): http://www.it-pro-berlin.de/
My stuff on PSGallery: https://www.powershellgallery.com/profiles/it-pro-berlin.de/
0
Previous Topic | Next Topic
Print
Reply

Quick Navigation:

Easily create a Forum Website with Website Toolbox.