Reputation: 625
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}
Upvotes: 1
Views: 94
Reputation: 40818
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)
Upvotes: 2
Reputation: 22831
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.
Upvotes: 2