Write-Warning

寫入警告訊息。

Syntax

Write-Warning
     [-Message] <String>
     [<CommonParameters>]

Description

Cmdlet 會將 Write-Warning 警告訊息寫入 PowerShell 主機。 警告的回應取決於用戶 $WarningPreference 變數的值,以及使用 WarningAction 一般參數。

範例

範例 1:撰寫警告訊息

此命令會顯示「警告:這隻是測試警告」訊息。

Write-Warning "This is only a test warning."

範例 2:將字串傳遞至 Write-Warning

這個指令顯示您可以使用管線運算子 (|) 將字串傳送至 Write-Warning。 您可以將字串儲存在變數中,如此命令所示,或將字串直接傳送至 Write-Warning

$w = "This is only a test warning."
$w | Write-Warning

範例 3:設定$WarningPreference變數並寫入警告

此範例顯示變數在命令上Write-Warning之值$WarningPreference的效果。

PS> $WarningPreference
Continue
PS> Write-Warning "This is only a test warning."
This is only a test warning.
PS> $WarningPreference = "SilentlyContinue"
PS> Write-Warning "This is only a test warning."
PS> $WarningPreference = "Stop"
PS> Write-Warning "This is only a test warning."
WARNING: This is only a test warning.
Write-Warning: The running command stopped because the preference variable "WarningPreference" or common parameter is set to Stop: This is only a test warning.

第一個命令會顯示變數的 $WarningPreference 預設值,也就是 Continue。 因此,當您撰寫警告時,會顯示警告訊息並繼續執行。

當您變更變數的值 $WarningPreference 時,命令的效果 Write-Warning 會再次變更。 的值 SilentlyContinue 會隱藏警告。 的值 Stop 會顯示警告,然後停止執行命令。

如需變數的詳細資訊 $WarningPreference ,請參閱 about_Preference_Variables

範例 4:設定 WarningAction 參數並寫入警告

這個範例顯示 Command 上 Write-Warning WarningAction 一般參數的效果。 您可以使用 WarningAction 一般參數搭配任何 Cmdlet 來判斷 PowerShell 如何響應該命令所產生的警告。 WarningAction 一般參數會覆寫唯一針對該特定命令的值$WarningPreference

PS> Write-Warning "This is only a test warning." -WarningAction Inquire
WARNING: This is only a test warning.
Confirm
Continue with this operation?
 [Y] Yes  [A] Yes to All  [H] Halt Command  [S] Suspend  [?] Help (default is "Y"):

此命令會 Write-Warning 使用 Cmdlet 來顯示警告。 WarningAction 一般參數,其值為 [查詢] 會指示系統在命令顯示警告時提示使用者。

如需 WarningAction 一般參數的詳細資訊,請參閱about_CommonParameters

參數

-Message

指定警告訊息。

Type:String
Aliases:Msg
Position:0
Default value:None
Required:True
Accept pipeline input:True
Accept wildcard characters:False

輸入

String

您可以使用管線將包含警告的字串傳送至此 Cmdlet。

輸出

None

此 Cmdlet 不會傳回任何輸出。 它只會寫入警告數據流。

備註

變數的 $WarningPreference 預設值為 Continue,其會顯示警告,然後繼續執行 命令。 若要判斷喜好設定變數的有效值,例如 $WarningPreference,請將它設定為隨機字元字串,例如 “abc”。 產生的錯誤訊息會列出有效的值。