Write-Warning
寫入警告訊息。
Syntax
Write-Warning
[-Message] <String>
[<CommonParameters>]
Description
Cmdlet Write-Warning
會將警告訊息寫入 PowerShell 主機。 警告的回應取決於用戶 $WarningPreference
變數的值,以及 使用 WarningAction 一般參數。
範例
範例 1︰寫入警告訊息
這個命令會顯示訊息 "WARNING: This is only a test warning."
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 message.
Write-Warning : Command execution stopped because the shell variable "WarningPreference" is set to Stop.
At line:1 char:14
+ Write-Warning <<<< "This is only a test message."
第一個命令會顯示變數的 $WarningPreference
預設值,也就是 Continue
。 因此,當您撰寫警告時,便會顯示該警告訊息,然後繼續執行。
當您變更變數的值時 $WarningPreference
,命令的效果 Write-Warning
會再次變更。 的值 SilentlyContinue
會隱藏警告。 的值 Stop
會顯示警告,然後停止執行命令。
如需變數的詳細資訊 $WarningPreference
,請參閱 about_Preference_Variables。
範例 4︰設定 WarningAction 參數和寫入警告
此範例顯示 WarningAction 一般參數在命令上 Write-Warning
的效果。 您可以使用 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 一般參數的值為 "Inquire" 時,會指示系統在命令顯示警告時提示使用者。
如需 WarningAction 一般參數的詳細資訊,請參閱 about_CommonParameters。
參數
-Message
指定警告訊息。
Type: | String |
Aliases: | Msg |
Position: | 0 |
Default value: | None |
Required: | True |
Accept pipeline input: | True |
Accept wildcard characters: | False |
輸入
您可以使用管線將包含警告的字串傳送至 Write-Warning
。
輸出
None
Write-Warning
只會寫入警告數據流。 它不會產生任何其他輸出。
備註
變數的 $WarningPreference
預設值為 Continue
,其會顯示警告,然後繼續執行命令。 若要判斷喜好設定變數的有效值,例如 $WarningPreference
,請將它設定為隨機字元字串,例如 “abc”。 產生的錯誤訊息會列出有效的值。