Powershell executing If Statement when condition is not met

789 Views Asked by At

I am having an issue with my If/Else statement where it will successfully prompt the user until either a "Y/y" or an "N/n" are entered and will store the proper response in the $input variable outside of the Do/Until loop but will execute the first block of code in the following If Statement whether $input is equal to "Y/y" or "N/n"

How can I make it so the If Statement will only execute when $input is equal to "Y/y" and otherwise if it's "N/n" just execute the empty else and move on to the next $program in $InstallList?

I've tried using an ElseIf and checking for "N/n" but it still only executes the first If Statement.

I've also put Write-Host for $input as a check after it leaves the Do/Until loop and it is the correct input but all falls apart when it moves on to executing the If/Else Statement.

Please help.

foreach($program in $InstallList){
    if($program -notin $Installed){
       $input = ""
       do {
            $input = Read-Host -Prompt "$($Program) is not installed would you like to install now? (y/n)"
          }
       until(($input -eq "y") -or ($input -eq "n"))
           if($input -eq "y")
                {
                    Write-ProgressHelper -Message "Installing $($Program)" -StepNumber ($stepCounter++)
                    Start-Sleep -Seconds 3
                    Start-Process $Software.$program -Wait
                    Write-Host "$($Software) installed`n"
                }
           else {}
    else{}
}
1

There are 1 best solutions below

0
mklement0 On
  • Abraham Zinala correctly states that use of $input as a custom variable should be avoided, because it is an automatic variable whose value is managed by PowerShell itself, namely to reflect pipeline input.

  • It is unfortunate that PowerShell even lets you assign a value, which is a problem that affects other automatic variables too - see this answer.

    • Technically, as long as you stay within the same scope, you can get away with using $input for custom purposes - though it should still be avoided.

    • Since this constraint is fulfilled in your code, use of $input is not the source of your problem; there is no obvious problem with your code.

Here's version of your code that avoids use of $input and streamlines ensuring that the user input is valid via the -in operator:

foreach ($program in $InstallList) {
  if ($program -notin $Installed) {
    do {
      $response = Read-Host -Prompt "$($Program) is not installed would you like to install now? (y/n)"
    } until ($response -in 'y', 'n')
    if ($response -eq 'y') {
      'yes' # ... install
    }
  }
}