And $_ refers to the current object in the pipeline
Indeed, the automatic $_
variable refers to the current pipeline object, but only in script blocks { ... }
, notably those passed to the ForEach-Object
and Where-Object
cmdlets.
Outside of script blocks it has no meaningful value.
Therefore, the immediate fix to your command is the following:
Get-Date | ForEach-Object { Write-Host $_ }
However, note that:
Write-Host
is is typically the wrong tool to use, unless the intent is to write to the display only, bypassing the success output stream and with it the ability to send output to other commands, capture it in a variable, or redirect it to a file.
- To output a value, use it by itself; e.g,
$value
, instead of Write-Host $value
(or use Write-Output $value
); see this answer. To explicitly print only to the display but with rich formatting, use Out-Host
.
Therefore, if merely outputting each pipeline input object is the goal, Get-Date | ForEach-Object { $_ }
would do, where the ForEach-Object
call is redundant if each input object is to simply be passed through (without transformation); that is, in the latter case just Get-Date
would do.
As for what you tried:
get-date|Write-Host "$_"
As noted, the use of $_
in this context is pointless, but the reason for the error message you saw is unrelated to that problem:
Instead, the reason for the error is that you're mistakenly trying to provide input to Write-Host
both via the pipeline Get-Date | Write-Host ...
and by way of an argument (... | Write-Host "..."
)
- Given that the argument (
"$_"
) (positionally) binds to the -Object
parameter, the pipeline input then has no parameter left to bind to, which causes the error at hand.