首页 > 开发 > PowerShell > 正文

PowerShell实现按条件终止管道的方法

2020-05-30 20:20:17
字体:
来源:转载
供稿:网友

有时你可能想在管道运行在某个特定的条件下,终止管道。今天来演示一个比较新颖的方式,它适用于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,它可以接受一个布尔条件参数,一旦条件成立,管道就会终止。

这个例子可以控制递归的深度,一旦检测到路径中包含了三个反斜杠,管道就会终止,当然你可以调节3到更大的整数,以增加扫描的文件夹深度。

这个诀窍需要管道必须嵌入在一个do 循环中,因为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)

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表