Home > Software design >  Need help using the IF statement in Powershell ISE
Need help using the IF statement in Powershell ISE

Time:10-13

I need help having my input correctly returned. When the user hits "1" it should say "Hello, Person!" and when the user hits "2" it should say "Goodbye Person!" I can only seem to get the second option to come up no matter what I change. I included the code, as well as a screenshot of the code. I would be grateful for anyone who is able to help me with this issue.

$title = "Convert Bat to Ps1"
$message = "Press 1 to say Hello, or Press 2 to say Goodbye"
$option1 = New-Object System.Management.Automation.Host.ChoiceDescription "1", "1"
$option2 = New-Object System.Management.Automation.Host.ChoiceDescription "2", "2"
$options = [System.Management.Automation.Host.ChoiceDescription[]]($option1, $option2)
$choice=$host.ui.PromptForChoice($title, $message, $options, 1)
If ($option1 -eq 1) {
  'Hello, Person!'
  exit
  } 
If ($option2 -ne 2) {
  'Goodbye, Person!'
  exit
} 

Image with the code I am having troubles with

CodePudding user response:

The outcome of the prompt choice will be stored in $choice, not in $Option1 or $Option2.

The value returned from PromptForChoice will be zero-indexed, so to test for option 1:

if($choice -eq 0){
  "Option 1 was chosen"
}

if($choice -eq 1){
  "Option 2 was chosen"
}

CodePudding user response:

You should not check on variable $option1 or $option2, but instead test the value of variable $choice, because that tells you whhich button was clicked.

Also, below I use a switch instead of multiple if\else:

$title   = "Convert Bat to Ps1"
$message = "Press 1 to say Hello, or Press 2 to say Goodbye"
$option1 = New-Object System.Management.Automation.Host.ChoiceDescription "1", "Option 1"
$option2 = New-Object System.Management.Automation.Host.ChoiceDescription "2", "Option 2"
$options = [System.Management.Automation.Host.ChoiceDescription[]]($option1, $option2)
$choice  = $host.ui.PromptForChoice($title, $message, $options, 1)

# $choice is now an Int32 value, it's the Index of the button that is clicked:
# 0 for option 1 and 1 for option 2

switch ($choice) {
    0 { 'Hello, Person!' }  # left out the exit here so you can stay in your PowerShell instance
    1 { 'Goodbye, Person!'; exit }
}
  • Related