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 |
输入
可以通过管道将包含警告的 Write-Warning
字符串传递给 。
输出
None
Write-Warning
仅写入警告流。 它不生成任何其他输出。
备注
变量的 $WarningPreference
默认值为 Continue
,显示警告,然后继续执行该命令。 若要确定首选项变量的有效值,例如 $WarningPreference
,请将其设置为随机字符字符串,例如“abc”。 生成的错误消息列出了有效值。