powershell脚本中的随机换行符

Random newline in powershell script

这是我的脚本,它在屏幕上显示时查找 wifi 网络的名称和密码:

$CmdL = @("Command1", "Command2", "WIFI NAME")
Trap  [System.Management.Automation.RuntimeException] {
    Write-Color "No such WiFi exists" -Color "Red"
    Continue
}
$S = $Null
$E = Get-AllWifiPasswords
Write-Host
$S = ($E | sls ($CmdL[2])).ToString().Trim()
Write-Color $S -Color "Green"
Write-Host

但是,如果找不到网络名称,则会在末尾添加一个尾随换行符:

(newline)
No such WiFi exists
(newline)
(newline)

我不知道为什么会有换行符,因为它不应该存在。怎样去掉才能使错误输出如下:

(newline)
No such WiFi exists
(newline)

额外的换行符来自于 Write-Color $S -Color "Green" also 在发生错误时执行,在这种情况下 $S 没有值,导致空行。

虽然后来引入的 trap is still supported, the try / catch / finally 语句提供了更大的灵活性和控制流的清晰度:

$CmdL = "Command1", "Command2", "WIFI NAME"
$S = $Null
$E = Get-AllWifiPasswords
Write-Host
try {
  # If the next statement causes a terminating error, 
  # which happens if the `sls` (`Select-String`) call has no output,
  # control is transferred to the `catch` block.
  $S = ($E | sls ($CmdL[2])).ToString().Trim()
  Write-Color $S -Color "Green"
}
catch {
  Write-Color "No such WiFi exists" -Color "Red"
}
Write-Host