powershell - 输入窗口关闭时关闭应用程序,如果输入为空或不对应 value 则返回启动

我写了一个小程序,但它有一个小问题。用户应该输入一个 value,它对应于一个数字。代码的问题是,无论何时您什么都不输入,输入一个不存在的 value 帽子或关闭输入窗口,它仍然会运行它后面的代码。

$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#

我希望应用程序在我退出输入窗口时关闭并返回脚本的开头,如果输入了错误的 value 或根本没有输入,但我是 PowerShell 的新手,似乎无法弄明白。

回答1

正如 https://stackoverflow.com/questions/72290287/close-application-when-input-window-is-closed-and-return-to-start-if-input-is-em#comment127714349_72290287 所评论的,您可以使用具有相应 Name/Values 的 Hashtable 而不是使用单独的变量来简化此操作。

另外,不要使用名为 $input 的变量,因为它是 PowerShell 中的 https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_automatic_variables?view=powershell-7#input

尝试这样的事情:

$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#

相似文章

随机推荐

最新文章