PowerShell method to implement conditional termination of pipelines

Source: Internet
Author: User
Tags continue terminates

This article mainly introduces the PowerShell to implement conditional termination of the pipeline, sometimes you may want to run in a certain condition, the pipeline to terminate the operation of the pipeline, this article explains such a method, the need for friends can refer to the

Sometimes you may want to terminate a pipe in a particular condition by running the pipe. Today to demonstrate a newer way, it applies to PowerShell 2.0 or later. First look at the code:

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 Filter Stop-pipeline {param ([scriptblock] $condition = {$true}) if (& $condition) {continue} $_} do {get-c Hilditem c:windows-recurse-erroraction Silentlycontinue | Stop-pipeline {($_. Fullname.tochararray ()-eq ""). COUNT-GT 3}} while ($false)

The pipe will recursively scan the Windows directory, the newly introduced command stop-pipeline, it can accept a Boolean condition parameter, and once the condition is set, the pipe will terminate.

This example controls the depth of recursion, and once the path is detected with three backslashes, the pipe terminates, and of course you can adjust 3 to a larger integer to increase the depth of the scanned folder.

This trick requires that the pipe be embedded in a Do loop because the stop-pipeline terminates the pipe by continue statement when the condition is satisfied.

It sounded a little clumsy, but it worked. To see another usage, let the pipe run for up to 10 seconds:

?

$start = Get-date $MaxSeconds =   do {get-childitem c:windows-recurse-erroraction silentlycontinue | Stop-pipeline {(get-date)-$start). Totalseconds-gt $MaxSeconds}} while ($false)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.