PowerShell實現(xiàn)按條件終止管道的方法
有時你可能想在管道運行在某個特定的條件下,終止管道。今天來演示一個比較新穎的方式,它適用于PowerShell 2.0或著更高版本。先看代碼:
filter Stop-Pipeline { param ( [scriptblock] $condition = {$true} ) if (& $condition) { continue } $_ } do { Get-ChildItem c:\Windows -Recurse -ErrorAction SilentlyContinue | Stop-Pipeline { ($_.FullName.ToCharArray() -eq '\').Count -gt 3 } } while ($false)
管道會遞歸的掃描windows目錄,新引入的命令stop-pipeline,它可以接受一個布爾條件參數(shù),一旦條件成立,管道就會終止。
這個例子可以控制遞歸的深度,一旦檢測到路徑中包含了三個反斜杠,管道就會終止,當然你可以調(diào)節(jié)3到更大的整數(shù),以增加掃描的文件夾深度。
這個訣竅需要管道必須嵌入在一個do 循環(huán)中,因為Stop-Pipeline在條件滿足時,是通過continue語句來終止管道的。
聽起來略微笨拙,但是效果杠杠的。再來看另一個用法,讓管道最多運行10秒鐘:
$start = Get-Date $MaxSeconds = 10 do { Get-ChildItem c:\Windows -Recurse -ErrorAction SilentlyContinue | Stop-Pipeline { ((Get-Date) - $start).TotalSeconds -gt $MaxSeconds } } while ($false)
相關文章
Windows Powershell 執(zhí)行外部命令
Windows PowerShell 在使用方面與 Cmd.exe 并無多大不同,只是 Windows PowerShell 的功能更為強大。與 Cmd.exe 一樣,Windows PowerShell 具有內(nèi)置的腳本編寫語言,不過它比 Cmd.exe 原始的批處理語言更為靈活。Cmd.exe 做到的事情,Windows PowerShell 幾乎都能做到。2014-08-08PowerShell調(diào)用Web測試工具Selenium實例
這篇文章主要介紹了PowerShell調(diào)用Web測試工具Selenium實例,又一篇PowerShell操作網(wǎng)頁的例子,需要的朋友可以參考下2014-07-07Powershell實現(xiàn)獲取電腦序列號功能腳本分享
這篇文章主要介紹了Powershell實現(xiàn)獲取電腦序列號功能腳本分享,本文直接給出實現(xiàn)代碼,需要的朋友可以參考下2015-03-03PowerShell中查看當前版本、Windows版本、.NET版本信息的代碼
這篇文章主要介紹了PowerShell中查看當前版本、Windows版本、.NET版本信息的代碼,需要的朋友可以參考下2014-08-08