powershell脚本中的随机换行符



这是我的一个脚本,当在屏幕上显示时,它可以找到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"在发生错误时也执行,在这种情况下$S没有值,导致空行。

虽然仍然支持trap,但稍后引入的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

最新更新