Write-Warning

写入警告消息。

语法

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

说明

Write-Warning cmdlet 向 Windows PowerShell 主机写入警告消息。 对警告的响应取决于用户$WarningPreference变量的值以及 WarningAction 常见参数的使用。

示例

示例 1:编写警告消息

PS C:\> Write-Warning "This is only a test warning."

此命令显示消息“WARNING:这只是测试警告”。

示例 2:将字符串传递给 Write-Warning

PS C:\> $w = "This is only a test warning."
PS C:\> $w | Write-Warning

此命令显示可以使用管道运算符 (|) 将字符串发送到 Write-Warning。 可以在变量中保存字符串,如此命令所示,也可以通过管道将字符串直接传递给 Write-Warning

示例 3:设置$WarningPreference变量并编写警告

PS C:\> $warningpreference
Continue PS C:\> Write-Warning "This is only a test warning."
This is only a test warning. PS C:\> $warningpreference = "SilentlyContinue"
PS C:\> Write-Warning "This is only a test warning."
PS C:\>
PS C:\> $warningpreference = "Stop"
PS C:\> 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."

此示例显示 Write-Warning 命令上$WarningPreference变量的值的效果。

第一个命令显示$WarningPreference变量的默认值,即 Continue。 因此,当你编写警告时,将显示警告消息,并继续执行。

更改$WarningPreference变量的值时,Write-Warning 命令的效果将再次更改。 SilentlyContinue 的值禁止显示警告。 “停止”值显示警告,然后停止执行命令。

有关$WarningPreference变量的详细信息,请参阅about_Preference_Variables。

示例 4:设置 WarningAction 参数并编写警告

PS C:\> 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 命令上 WarningAction 公共参数的效果。 可以在任何 cmdlet 中使用 WarningAction 通用参数来确定 Windows PowerShell 如何响应该命令生成的警告。 WarningAction 通用参数仅覆盖该特定命令$WarningPreference的值。

此命令使用 Write-Warning cmdlet 来显示警告。 WarningAction 公共参数,其值为“查询”指示系统在命令显示警告时提示用户。

有关 WarningAction 常见参数的详细信息,请参阅about_CommonParameters。

参数

-Message

指定警告消息。

类型:String
别名:Msg
Position:0
默认值:None
必需:True
接受管道输入:True
接受通配符:False

输入

String

可以通过管道将包含警告的字符串传递给 Write-Warning

输出

None

写入警告 只写入警告流。 它不会生成任何其他输出。

备注

  • $WarningPreference变量的默认值为 Continue,显示警告,然后继续执行命令。 若要确定首选项变量(如 $WarningPreference)的有效值,请将其设置为随机字符字符串,例如“abc”。 生成的错误消息将列出有效值。