Powershell Bool 返回数组

use*_*062 2 powershell

我正在尝试从函数返回 $true 或 $false ,并得到一个 array 。如果我删除 listBox 消息,它会按预期工作。有谁知道为什么?

function TestEmptyFields()
{
  $empty= $false

  $listBox1.Items.Add("Testing fields")

  if ($txtPrtName.get_text()-eq "")
  {
    $listBox1.Items.Add("Empty name")
    $empty= $true
  }
  elseif ($txtPrtIP.get_text() -eq "")
  {
    $listBox1.Items.Add("Empty Ip")
    $empty= $true
  } 
  else 
  {
    $empty= $false
  }

  $listBox1.Items.Add($txtPrtName.get_text())
  $listBox1.Items.Add($txtPrtIP.get_text())

  return $empty
}
Run Code Online (Sandbox Code Playgroud)

但它像这样工作正常:

function TestEmptyFields()
{
  if($txtPrtName.get_text()-eq "")
  {
    return $true
  }
  elseif ($txtPrtIP.get_text() -eq "")
  {
    return $true
  }
  else
  {
    return $false
  }
}
Run Code Online (Sandbox Code Playgroud)

Ant*_*ace 5

在 powershell 中,return $empty它在功能上等同于$empty ; return- 实施该行为是为了让具有 C 风格语言背景的人更轻松,但实际上返回的比您想象的要多!列表框也返回内容。事实上,任何未分配给变量或以其他方式使其输出无效的内容都将到达输出流。要解决此问题,请尝试将列表框转换为[void]如下所示:

[void] $listBox1.Items.Add("Testing fields")
Run Code Online (Sandbox Code Playgroud)

回顾这份TechNet 指南,了解在表单上下文中正确使用 Listboxes可能也没什么坏处。