Difference between ForEach and ForEach-Object in powershell

前端 未结 4 584
失恋的感觉
失恋的感觉 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:47

    They're different commands for different purposes. The ForEach-Object cmdlet is used in the pipeline, and you use either $PSItem or $_ to refer to the current object in order to run a {scriptblock} like so:

    1..5 | ForEach-Object {$_}
    
    >1
    >2
    >3
    >4
    >5
    

    Now, you can also use a very similiar looking keyword, ForEach, at the beginning of a line. In this case, you can run a {scriptblock} in which you define the variable name, like this:

    ForEach ($number in 1..5){$number}
    >1
    >2
    >3
    >4
    >5
    

    The core difference here is where you use the command, one is used in the midst of a pipeline, while the other starts its own pipeline. In production style scripts, I'd recommend using the ForEach keyword instead of the cmdlet.

提交回复
热议问题