如何忽略警告错误? [英] How to ignore warning errors?
问题描述
我有以下 PowerShell 脚本.它选取给定 IP 地址内计算机的 NetBIOS 名称.我正在使用管道将结果转储到文本文件中.问题是,如果 IP 地址不可用,则会打印警告.
I have the following PowerShell script. It picks up the NetBIOS name of computers within a given IP address. I'm using a pipe so as to dump the results into a text file. The problem is that if an IP address is not available, a warning is printed.
这是 PowerShell 脚本:
This is the PowerShell script:
function Get-ComputerNameByIP {
param( $IPAddress = $null )
BEGIN {
$prefBackup = $WarningPreference
$WarningPreference = 'SilentlyContinue'
}
PROCESS {
if ($IPAddress -and $_) {
throw ‘Please use either pipeline or input parameter’
break
} elseif ($IPAddress) {
([System.Net.Dns]::GetHostbyAddress($IPAddress))
}
} else {
$IPAddress = Read-Host "Please supply the IP Address"
[System.Net.Dns]::GetHostbyAddress($IPAddress)
}
}
END {
$WarningPreference = $prefBackup
}
这是我希望忽略的错误消息:
This is the error message I wish to ignore:
警告:请求的名称有效,但未找到请求类型的数据
WARNING: The requested name is valid, but no data of the requested type was found
推荐答案
您想抑制警告,而不是错误.警告可以通过设置 $WarningPreference
变量到 SilentlyContinue
:
You want to suppress warnings, not errors. Warnings can be silenced completely by setting the $WarningPreference
variable to SilentlyContinue
:
PS C:\> Write-Warning 'foo'
WARNING: foo
PS C:\> $prefBackup = $WarningPreference
PS C:\> $WarningPreference = 'SilentlyContinue'
PS C:\> Write-Warning 'foo'
PS C:\> $WarningPreference = $prefBackup
PS C:\> Write-Warning 'foo'
WARNING: foo
该设置与当前范围有关,因此如果您想取消函数的所有警告,只需在函数的开头设置首选项:
The setting pertains to the current scope, so if you want to suppress all warnings for your function you'd simply set the preference at the beginning of your function:
function Get-ComputerNameByIP {
param( $IPAddress = $null )
BEGIN {
$WarningPreference = 'SilentlyContinue'
}
PROCESS {
if ($IPAddress -and $_) {
throw ‘Please use either pipeline or input parameter’
break
} elseif ($IPAddress) {
[System.Net.Dns]::GetHostbyAddress($IPAddress)
}
[System.Net.Dns]::GetHostbyAddress($_)
} else {
$IPAddress = Read-Host "Please supply the IP Address"
[System.Net.Dns]::GetHostbyAddress($IPAddress)
}
}
END {}
}
如果您只想针对特定语句抑制警告,更简单的方法是重定向警告输出流到$null
:
If you want warnings suppressed for specific statements only, a simpler way is to redirect the warning output stream to $null
:
[System.Net.Dns]::GetHostbyAddress($IPAddress) 3>$null
警告流重定向仅在 PowerShell v3 及更新版本中可用.
Warning stream redirection is only available in PowerShell v3 and newer, though.
这篇关于如何忽略警告错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!