I have a [pscustomobject] with a property id. According to PowerShell documentation, the parameter '-id' can be passed through the pipeline using ByPropertyName. I discovered that the approach with ForEach-Object works (although I don't understand why), while the approach without ForEach-Object does not.
$obj = [pscustomobject]@{id=4444}
# doesn't work
$obj | get-process -id $_.id
# it works
$obj | foreach{get-process -id $_.id}
Apparently the "foreach" does the trick, but why?
The binding happens by pipeline already, you don't need to manually pass the argument, moreover,
$_(PSItem) is only automatically populated in the context of scriptblock and your second statement has no scriptblock.As to why the
ForEach-Objectexample works, simply because you're passing the value ofidproperty as argument to the-Idparameter, it is pretty much the same as: