Windows PowerShell で出力を書く方法
-
PowerShell の
Write-OutputCmdlet -
PowerShell の
Write-HostCmdlet -
PowerShell の
Write-DebugCmdlet -
PowerShell の
Write-VerboseCmdlet
コンソールへの出力を書くことは、ユーザーに正しいフィードバックを提供するために、どの言語においても重要なプロセスです。しかし、Windows PowerShell には出力を印刷するための複数の方法があります。この記事では、さまざまな Write cmdlet の違いを説明し、それを使用できる状況と場所を提供します。
cmdlet の議論に入る前に、Windows PowerShell が二重引用符 ("") で囲まれた単一行を出力できることは注目に値します。
例のコード:
"Hello World!"
出力:
Hello World!
この構文は、文字列リテラル式と隠れたパイプラインのおかげで Windows PowerShell で可能です。この構文は、以下の例のコードと同等です。
例のコード:
"Hello World!" | Out-Host
一方、Out-Host cmdlet は、表示のために先行されたオブジェクトを送信します。
PowerShell の Write-Output Cmdlet
Windows PowerShell における最初の印刷方法は Write-Output cmdlet です。この cmdlet は、PowerShell スクリプト環境内で印刷するための基本構文です。これは、他の多くの言語の基本的な印刷コマンド (print や stdout) に相当します。
例のコード:
Write-Output "Hello World!"
出力:
Hello World!
PowerShell の Write-Host Cmdlet
Write-Host cmdlet は、前の方法である Write-Output に似た別の印刷方法です。ただし、-BackgroundColor と -ForegroundColor パラメータを使用して異なる色を出力できる点が異なります。
PowerShell の Write-Debug Cmdlet
Write-Debug cmdlet は、Windows PowerShell で印刷するための別の方法です。ただし、これは通常、スクリプト環境でデバッグメッセージを印刷するためにもっと使用されます。メッセージはデフォルトで表示されませんが、$debugPreference 変数を使用して表示することができます。
例のコード:
Write-Debug "Error on line 1 but will silently continue."
$debugPreference = "Continue"
Write-Debug "Error on line 3 will now be displayed"
出力:
DEBUG: Error on line 3 will now be displayed
PowerShell の Write-Verbose Cmdlet
Write-Verbose cmdlet は、Windows PowerShell の冗長メッセージストリームにテキストを書き込みます。冗長メッセージストリームは、コマンド処理に関するより多くの情報を提供するように定義されています。Write-Debug と同様に、冗長メッセージはデフォルトで表示されませんが、変数 $VerbosePreference を使用するか、スイッチパラメータ -Verbose を追加することで表示することができます。
例のコード:
Write-Verbose -Message "This will not be displayed."
Write-Verbose -Message "This will be displayed" -Verbose
出力:
VERBOSE: This will be displayed
Marion specializes in anything Microsoft-related and always tries to work and apply code in an IT infrastructure.
LinkedIn