是否可以从过滤器中终止或停止PowerShell管道 [英] Is it possible to terminate or stop a PowerShell pipeline from within a filter

查看:138
本文介绍了是否可以从过滤器中终止或停止PowerShell管道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个简单的PowerShell过滤器,如果当前对象的日期在指定的开始日期和结束日期之间,则将其向下推送到管道中.流水线中的对象始终按升序排列,因此一旦日期超过指定的结束日期,我就知道我的工作已经完成,我想告诉流水线上游命令可以放弃其工作,以便流水线可以完成工作.我正在读取一些非常大的日志文件,而我经常想只检查其中一部分日志.我很确定这是不可能的,但我想请确保.

I have written a simple PowerShell filter that pushes the current object down the pipeline if its date is between the specified begin and end date. The objects coming down the pipeline are always in ascending date order so as soon as the date exceeds the specified end date I know my work is done and I would like to let tell the pipeline that the upstream commands can abandon their work so that the pipeline can finish its work. I am reading some very large log files and I will frequently want to examine just a portion of the log. I am pretty sure this is not possible but I wanted to ask to be sure.

推荐答案

可以用其他任何方式破坏管道,否则将破坏外部循环或完全停止脚本执行(例如引发异常).然后,解决方案是将管道包装在一个循环中,如果需要停止管道,可以中断该循环.例如,以下代码将从管道返回第一项,然后通过中断外部do-while循环来中断管道:

It is possible to break a pipeline with anything that would otherwise break an outside loop or halt script execution altogether (like throwing an exception). The solution then is to wrap the pipeline in a loop that you can break if you need to stop the pipeline. For example, the below code will return the first item from the pipeline and then break the pipeline by breaking the outside do-while loop:

do {
    Get-ChildItem|% { $_;break }
} while ($false)

此功能可以包装成这样的功能,其中最后一行完成与上面相同的功能:

This functionality can be wrapped into a function like this, where the last line accomplishes the same thing as above:

function Breakable-Pipeline([ScriptBlock]$ScriptBlock) {
    do {
        . $ScriptBlock
    } while ($false)
}

Breakable-Pipeline { Get-ChildItem|% { $_;break } }

这篇关于是否可以从过滤器中终止或停止PowerShell管道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆