Home > Enterprise >  Close application when input window is closed and return to start if input is empty or doesn't
Close application when input window is closed and return to start if input is empty or doesn't

Time:05-19

I wrote a small program, but it has a slight issue. The user is supposed to input a value, which corresponds to a number. The problem with the code is that whenever you enter nothing at all, enter a value hat doesn't exist or close the input window, it still runs the code following it.

$A = 87
$B = 130
$C = 80
$D = 83
$E = 78
$F = 92
 
$input = $(
      Add-Type -AssemblyName Microsoft.VisualBasic
      [Microsoft.VisualBasic.Interaction]::InputBox('Select a computer','Test', 'row/column')
     )

 

  if($input -eq 'E2')
 {
     Set-Variable -Name "ip" -Value $A
 }
 
  if($input -eq 'A2')
  {
   
    Set-Variable -Name "ip" -Value $B 
  }
  
  if($input -eq 'D3')
  {
   
    Set-Variable -Name "ip" -Value $C 
  }
  
  if($input -eq 'C3')
  {
   
    Set-Variable -Name "ip" -Value $D 
  }
  
  if($input -eq 'E4')
  {
     Set-Variable -Name "ip" -Value $E
  }
  
  if($input -eq 'F4')
 {
     Set-Variable -Name "ip" -Value $F
 }
   
#remaining code#

I'd like the application to close when I X out of the input window & return to the beginning of the script if a wrong value or none is entered at all, but I'm new to PowerShell and can't seem to figure it out.

CodePudding user response:

As Jeroen Mosterd commented, you can make this much easier using a Hashtable with corresponding Name/Values instead of using separate variables.

Also, don't use a variable called $input because that is a Automatic variable in PowerShell

Try something like this:

$hash = @{
    E2 = 87
    A2 = 130
    D3 = 80
    C3 = 83
    E4 = 78
    F4 = 92
}

Add-Type -AssemblyName Microsoft.VisualBasic

do {
    $ip = $null
    $choice = [Microsoft.VisualBasic.Interaction]::InputBox('Type the name of a computer','Test')
    # exit the loop if the user cancels the box or clicks OK with an emty value
    if ([string]::IsNullOrWhiteSpace($choice)) { break }

    $ip = $hash[$choice]
} until ($ip)


if (!$ip) { exit }

# remaining code#
  • Related