简体   繁体   中英

Does PowerShell use Write-Host or Write-Output by default

When I type "my text" on a line by itself, the text is output to the console, but is that using Write-Host or Write-Output by default (and how can I see that - I mean, I tried using | Get-Member to get a clue but was not sure)?

The reason that I'm asking is that I'm aware of the known issues with Write-Host breaking sequential output in a script that has pipeline commands nearby.

So, I did a small test to figure this one out. Out-Host and Write-Host, cannot be redirected to any stream whatsoever. This is how they work, they simply write to whatever is the default calling stream.

Using this logic,

"string1" | Out-host *>$null

will give the output as "string1", since it cannot be re-directed. But,

"string1" *>$null

will display no output, hence proving, writing any text is the same as passing it to the Write-Output cmdlet:

# All are same
"string"
"string" | Write-Output
Write-Output "string"

There are several methods of displaying text in powershell. The write-host displays the text itself in the console. It is host dependent. Next, write-output writes output from a pipeline, so the next command can receive it. It's not necessary it will display text every time. [Console]::WriteLine is quite same like write-host . And Out-Default sends the output to the default formatter and to the default output cmdlet. It is automatically added by powershell itself at the end of every pipeline. If the input object is not string it decides what to do. So, it is Out-Default which does this.

Write-output.

write-host hi | measure | % count
hi
0

write-output hi | measure | % count
1

'hi' | measure | % count             
1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM