這是我擁有的一個腳本,它在螢屏上顯示時查找 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)
uj5u.com熱心網友回復:
額外的換行符來自這樣一個事實,它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
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/351178.html
上一篇:雅虎、領英接連退出中國,開發者:GitHub 也會受到影響嗎?
下一篇:Powershell:為什么("111"-match"111-XD")回傳false而("111-XD"-match"111&qu
