如何忽略警告错误?

Obb*_*bby 4 powershell suppress-warnings powershell-ise

我有以下 PowerShell 脚本。它选取给定 IP 地址内计算机的 NetBIOS 名称。我正在使用管道将结果转储到文本文件中。问题在于,如果 IP 地址不可用,则会打印警告。

这是 PowerShell 脚本:

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
}
Run Code Online (Sandbox Code Playgroud)

这是我希望忽略的错误消息:

警告:请求的名称有效,但未找到请求类型的数据

mig*_*llo 13

您可以将公共参数-WarningAction:SilentlyContinue与生成警告的命令一起使用。这比$WarningPreference在执行命令之前单独覆盖并在执行命令之后恢复它要好,如上面所建议的 - 这个参数基本上可以为您做到这一点。

$WarningPreferencewarningAction 参数覆盖当前命令的变量值。由于该变量的默认值为$WarningPreferenceContinue,因此除非您使用WarningAction 参数,否则将显示警告并继续执行。

在这里查看更多内容。


Ans*_*ers 5

您想抑制警告,而不是错误。通过将$WarningPreference变量设置为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
Run Code Online (Sandbox Code Playgroud)

该设置与当前范围有关,因此如果您想取消函数的所有警告,只需在函数的开头设置首选项:

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
Run Code Online (Sandbox Code Playgroud)

如果您只想为特定语句抑制警告,更简单的方法是警告输出流重定向$null

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 {}
}
Run Code Online (Sandbox Code Playgroud)

但是,警告流重定向仅在 PowerShell v3 及更高版本中可用。


Ves*_*per 4

$ErrorActionPreference = 'SilentlyContinue'
Run Code Online (Sandbox Code Playgroud)

此全局变量控制那些提供间歇性(非终止)错误和警告的命令的错误输出。您的错误属于此类,因此将首选项设置为默默地继续抑制这些警告。