Named blocks and return

The return keyword may be used to gracefully end the execution of a piece of code.

The return keyword is often confused with return in C#, where it explicitly returns a thing from a method. In PowerShell, return has a slightly different purpose.

When a named block is executing, the return keyword may be used to end the processing of a block early without stopping the rest of the pipeline.

For example, a return statement in the process block ends early in certain cases. The end block will continue to execute as normal:

function Invoke-Return {
process {
if ($_ -gt 2) {
return
}
$_
}

end {
'All done'
}
}

When run, the process block will end early when the condition is met:

PS> 1..10 | Invoke-Return
1
2
All done
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.225.255.134