Reputation: 11
I just can't get the read host yes/no prompt to work properly.
do { $answer = Read-Host "yes or no" }
until ("yes","no" -ccontains $answer)
if ($answer = "$yes"){
write-host "time is enabled"
} Else {
write-host "time service disabled"
}
It always jumps to else, sorry I'm kinda new.
cheers
Upvotes: 0
Views: 2882
Reputation: 13422
The primary issue is with the line if ($answer = "$yes")
.
=
always means assignment in PowerShell. To compare the values, you would use the -eq
operator."$yes"
is also inadvertently using variable expansion. Since the variable $yes
is not defined, the operand evaluates to the empty string, ""
.$answer
is overwritten with ""
, which is then evaluated by the if
statement as being logically false, thus entering the else
block.Changing the line to if( $answer -eq 'yes' )
will fix the issue.
Also, the use of the case-sensitive -ccontains
operator in the do
/until
loop is more restrictive than it needs to be. The default in PowerShell is to do case-insensitive comparisons, so that entering yes
, or Yes
, or YES
will all pass.
Alternatively, if case-sensitivity is important for your scenario, you might want to consistently use case-sensitive operators throughout your script (i.e. using -ceq
in your if
statement).
For more information, see the help topic about_Comparison_Operators
.
Upvotes: 0
Reputation: 2305
The code you supplied is contains a typo, -ccontains should be -contains
Also, the line: ($answer = "$yes") is comparing the $answer variable to the $yes variable, which does not exist in the snippet you provided.
If you're trying to see if the $answer variable is equal to "yes", then remove the dollar sign from the beginning of the string.
Here is the corrected version:
do { $answer = Read-Host "Yes or no" }
until ("yes","no" -contains $answer)
if ($answer -eq "yes")
{
write-host "time is enabled"
}
else
{
write-host "time service disabled"
}
Upvotes: 0
Reputation: 1639
Common syntax error - don't use =
where you mean -eq
:)
if ($answer -eq "yes"){
Upvotes: 4