「Write-Host」、「Write-Output」、または「[console]::WriteLine」の違いは何ですか? 質問する

「Write-Host」、「Write-Output」、または「[console]::WriteLine」の違いは何ですか? 質問する

メッセージを出力する方法はいくつかあります。Write-Host、、Write-Outputまたはを介して出力する場合の実質的な違いは何ですか[console]::WriteLine?

また、次の点にも気づきました:

write-host "count=" + $count

+出力に含まれます。なぜでしょうか? 式は書き出される前に評価されて、連結された単一の文字列を生成するべきではないでしょうか?

ベストアンサー1

Write-Outputパイプラインでデータを送信したいが、必ずしも画面に表示したくない場合に使用します。パイプラインは、out-default他に何も使用しない限り、最終的にデータを書き込みます。

Write-Host反対のことをしたいときに使用する必要があります。

[console]::WriteLineWrite-Host基本的には舞台裏で行われていることです。

このデモ コードを実行し、結果を調べます。

function Test-Output {
    Write-Output "Hello World"
}

function Test-Output2 {
    Write-Host "Hello World" -foreground Green
}

function Receive-Output {
    process { Write-Host $_ -foreground Yellow }
}

#Output piped to another function, not displayed in first.
Test-Output | Receive-Output

#Output not piped to 2nd function, only displayed in first.
Test-Output2 | Receive-Output 

#Pipeline sends to Out-Default at the end.
Test-Output 

連結操作を括弧で囲む必要があります。そうすることで、PowerShellは連結をパラメータリストをトークン化する前に処理しますWrite-Host。または、文字列補間を使用します。

write-host ("count=" + $count)
# or
write-host "count=$count"

ところで、パイプラインの仕組みを Jeffrey Snover が説明しているこのビデオをご覧ください。私が PowerShell を学び始めた頃、これがパイプラインの仕組みに関する最も役立つ説明だとわかりました。

おすすめ記事