Write-Warning

写入一条警告消息。

语法

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

说明

Write-Warning cmdlet 将警告消息写入 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 变量并写入警告

此示例展示了 $WarningPreference 变量的值对 Write-Warning 命令的效果。

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 参数并写入警告

此示例展示了 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 显示警告。 值为 Inquire 的 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”。 生成的错误消息会列出有效值。