I was working on a PowerShell script to add users to Active Directory from a csv file by generating usernames from their first and last names. After making an initial username (first initial + last name), it checks if this username already exists. If it does, it asks for confirmation to try first initial + middle initial + last name. Currently, I do this with the following code:

write-host "Default username is already taken. Please press enter tocontinue or type NO to skip importing this user.
$PROMPT = Read-Host '>'

#If not skipped, continue with logic
if ($PROMPT -ne "no")

This seems to work, but if I accidentially press enter two times, for example, it not only confirms the current prompt but the next one as well. I'm pretty new to PowerShell, so I'm guessing there's a better way to do this. Any advice?


enter image description here

You could pop up some sort of message box. There are a few different ways to do that. Here's one easy way:

$wshell = New-Object -ComObject Wscript.Shell
$msg = "Default username is already taken. Continue?"
$r = $wshell.Popup($msg, 0, "Warning", 4)
if ($r -eq 6)
    # Continue ...

For an explanation of the mysterious numbers 4 and 6, see Popup Method.


You could alter your script such that the input should be y/yes or n/no. If it's not either of those, prompt again.

This would eliminate accidentally confirming a change, but would require that you specifically press a key then enter to confirm or skip.

Possibly better ways to do this, but that's my initial thought.

As an aside, you can skip the $PROMPT = $PROMPT.ToLower() line. -eq isn't case sensitive, so the following works:

PS C:\> 'NO' -eq 'no'

If you want string comparison to be case sensitive, look for the operators that start with a c, like -ceq.

  • Thanks, I didn't know that! I figured I could do something like this, just wondered why it was saving multiple inputs - I feel like it will probably do the same thing if I typed "y" multiple times, though that's harder to do accidentially – Krixvar Aug 13 '15 at 15:49
  • @Krixvar, Read-Host takes everything you type up until you press enter, so if you pressed y twice, you'd just end up with a string of 'yy' waiting for you to press enter (and fail if you do hit enter because it isn't a valid response.) As to why... I don't know. I don't even know if it is unique to PowerShell. You can see this all over the place by running a long running command, hitting enter a few times while it runs, and then when it's finished you'll see a bunch of prompts pop up underneath as it processes those key presses. – Windos Aug 13 '15 at 20:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.