Why $ _ does not return the complete object Why $ _ does not return the complete object powershell powershell

Why $ _ does not return the complete object


$_ is returning the entire object, however Write-Host expects a string, and so the .ToString() method is called on the object. In the case of System.IO.FileInfo its ToString() is overridden to output the name of the file.

Try this and see for yourself:

Get-ChildItem | %{Write-Host $_.ToString()}

Get-ChildItem | %{Write-Host $_.GetType()}

Get-ChildItem | %{Write-Host $_.Mode}


Write-Host is for writing information out to the console, so objects are formatted as strings, similar to if you had done gci | % { "$_" } (except the latter writes to the output stream not directly to the host).

If you want to write directly to the console but the same formatting you would see if sent to the console implicitly, use Out-Host as recommended by mklement0:

Get-ChildItem | Out-Host

His comment in full:

I suggest using Out-Host directly; also, perhaps surprisingly, Write-Host "$_" is not always the same as Write-Host $_, because the latter results in .ToString() getting called, which defaults to a culture-sensitive representation (where available), whereas PowerShell's string interpolation by design always uses the invariant culture