Difference between ForEach and ForEach-Object in powershell

前端 未结 4 581
失恋的感觉
失恋的感觉 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 06:49

    Apart from the technical differences that have been mentioned before, here are some practical differences, for sake of completeness (see also):

    1.) In a pipeline, you do not know the total count of the processed items. This is a situation where you would opt to acquire the complete list first and then do a foreach-loop.

    Example:

    $files = gci "c:\fakepath"
    $i = 0
    foreach ($file in $files) {
        $i++
        Write-Host "$i / $($files.Count) processed"
    }
    

    2.) With an existing list, the foreach loop is faster than then pipeline version, because the script block does not have to be invoked each time. (But the difference might be negligible depending on the work you do and the number of items.)

    Example:

    $items = 0..100000
    Measure-Command { $items | ForEach-Object { $_ } }
    # ~500ms on my machine
    Measure-Command { foreach ($i in $items) { $i } }
    # ~70ms on my machine
    

提交回复
热议问题