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) |