Difference between ForEach and ForEach-Object in powershell

前端 未结 4 570
失恋的感觉
失恋的感觉 2020-12-01 06:09

Is there any difference between ForEach and ForEach-Object ?

I have a small code like this, works fine

$txt = Get-Content \         


        
4条回答
  •  隐瞒了意图╮
    2020-12-01 07:07

    Both the previous answers are correct, but https://blogs.technet.microsoft.com/heyscriptingguy/2014/07/08/getting-to-know-foreach-and-foreach-object/ has both a good summary:

    When you are piping input into ForEach, it is the alias for ForEach-Object. But when you place ForEach at the beginning of the line, it is a Windows PowerShell statement.

    and more details:

    The ForEach statement loads all of the items up front into a collection before processing them one at a time. ForEach-Object expects the items to be streamed via the pipeline, thus lowering the memory requirements, but at the same time, taking a performance hit.

    He then includes some performance measurements and concludes:

    So which one do you use? Well, the answer is, “It depends.” You can iterate through a collection of items by using either the ForEach statement or the ForEach-Object cmdlet. ForEach is perfect if you have plenty of memory, want the best performance, and do not care about passing the output to another command via the pipeline. ForEach-Object (with its aliases % and ForEach) take input from the pipeline. Although it is slower to process everything, it gives you the benefit of Begin, Process, and End blocks. In addition, it allows you to stream the objects to another command via the pipeline. In the end, use the approach that best fits your requirement and the capability of your system.

提交回复
热议问题