如何在 Windows PowerShell 中輸出結果
-
PowerShell 中的
Write-Output
命令 -
PowerShell 中的
Write-Host
命令 -
PowerShell 中的
Write-Debug
命令 -
PowerShell 中的
Write-Verbose
命令

將輸出寫入控制台是任何語言中的一個基本過程,因為它正確地向用戶提供反饋。然而,在 Windows PowerShell 中,有多種打印輸出的方式。本文將區分多個 Write
命令,並提供我們何時何地可以使用它們的情境。
在我們進入命令的討論之前,值得注意的是 Windows PowerShell 可以通過用雙引號(""
)包圍單行文本來輸出某些內容。
範例代碼:
"Hello World!"
輸出:
Hello World!
這種語法在 Windows PowerShell 中是可行的,因為字符串字面量表達式和隱藏的管道。這種語法相當於下面的範例代碼。
範例代碼:
"Hello World!" | Out-Host
另一方面,Out-Host
命令將前置對象發送到顯示。
PowerShell 中的 Write-Output
命令
Windows PowerShell 中的第一種打印方法是 Write-Output
命令。這個命令是我們的 PowerShell 腳本環境內打印的基本語法。我們可以將其與許多語言的基本打印命令,如 print
和 stdout
相提並論。
範例代碼:
Write-Output "Hello World!"
輸出:
Hello World!
PowerShell 中的 Write-Host
命令
Write-Host
命令是另一種打印方法,類似於先前的 Write-Output
。唯一的區別是,它可以使用參數 -BackgroundColor
和 -ForegroundColor
輸出不同的顏色。
PowerShell 中的 Write-Debug
命令
Write-Debug
命令也是 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
命令
Write-Verbose
命令將文本寫入 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