1

I have a strange problem. Want to create a script that input user to insert a string and than loop again in the input request until leaved blank.

The script work well in PowerGUI continuing prompting a input request until i press only [Enter] than the script go on. The problem appear when i try to use the script on a powershell shell. Pressing only [Enter] let the DoWhile cycle continue to prompt me the input request without possibility to stop it unless CTRL-Z it.

Some ideas to why?

[Int] $num = 1
[Array] $conts = @()

do {
    $a = read-host "Indirizzo mail Contatto $num`?"
    if ($a -ne $null) {
            $num++
            $conts += $a
    } 

} while($a -ne $null)

Function CreaContatto {
    $mailContact = $args 
    $aliasContact = $args -replace ("@","_")
    New-MailContact -ExternalEmailAddress $mailContact -Name $mailContact -Alias $aliasContact
}

ForEach ($cont in $conts) {CreaContatto $cont}

2 Answers 2

2

My guess is that PowerGUI implements a custom host and that returns null from read-host when there is no input. The standard PowerShell host doesn't do that, it returns an empty string (unless you hit ctrl-z which signals end-of-file). Since both are falsy you can do this:

do {
    $a = read-host "Indirizzo mail Contatto $num`?"
    if ($a) {
        $num++
        $conts += $a
    }
} while($a)
Sign up to request clarification or add additional context in comments.

1 Comment

Many thanks. You are right about PowerGUI return. Analysing the variable value during the script run your supposition are right. PowerGUI assign the $null value when string are empty. Probably Powershell doesn't do.
2

Thing is, $a is not null when pressing Enter, it is a newline. You can see this if you add a write-host $a below your if statement.

In this case, I'd suggest using a regex:

do {
    $a = read-host "Indirizzo mail Contatto $num`?"
    if ($a -ne $null) {
            $num++
            $conts += $a
    } 

} while($a -match '.+')

This says that $a has to be one or more characters.

1 Comment

Your answer is right but for simplicity I choose the "mike z" one. Need to implement more right answer on StackOverflow.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.