The pipeline variable is useful when you have nested foreach loops.
But also it allows to have a meaningful name for the pipeline object inside your Process block.
And it avoids having to do an additional assignment inside the Process block.
For example, instead of doing
Get-Datacenter |ForEach-Object -Process {
$dc = $_
Get-Cluster -Location $dc |
Select @{N='Datacenter';E={$dc.Name}},
@{N='Cluster';E={$_.Name}}
}
you can do
Get-Datacenter -PipelineVariable dc
|ForEach-Object -Process {
Get-Cluster -Location $dc |
Select @{N='Datacenter';E={$dc.Name}},
@{N='Cluster';E={$_.Name}}
}
Admittedly this is a personal preference, both solutions work.
But, personally, I prefer the more concise code with the PipelineVariable.