您现在的位置是:网站首页> 编程资料编程资料
PowerShell实现按条件终止管道的方法_PowerShell_
2023-05-26
571人已围观
简介 PowerShell实现按条件终止管道的方法_PowerShell_
有时你可能想在管道运行在某个特定的条件下,终止管道。今天来演示一个比较新颖的方式,它适用于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) 您可能感兴趣的文章:
相关内容
- Powershell互斥参数使用实例_PowerShell_
- PowerShell实现统计函数嵌套深度_PowerShell_
- PowerShell在控制台输出特殊符号的方法_PowerShell_
- PowerShell实现查询打开某个文件的默认应用程序_PowerShell_
- PowerShell实现在字符串中查找大写字母_PowerShell_
- Win10下自带的PowerShell读取文件哈希值_PowerShell_
- powershell与cmd的异同汇总_PowerShell_
- 脚本实现SSL证书到期监控示例_PowerShell_
- 自动设置安卓手机wifi代理的PowerShell脚本_PowerShell_
- PowerShell基本使用教程_PowerShell_
