How to ignore warning errors?
Asked Answered
D

5

8

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.

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

Donovan answered 8/6, 2015 at 13:2 Comment(1)
Just to make sure: do you get a warning or an error? Warnings start with the text WARNING: and are normally displayed as yellow text, while errors are normally displayed as red text and include a stacktrace.Huskey
P
16

You can use common parameter -WarningAction:SilentlyContinue with the command that generates warning. It's better than separately overriding $WarningPreference before executing the command and reverting it back afterwards as was suggested above - this parameter basically does that for you.

The WarningAction parameter overrides the value of the $WarningPreference variable for the current command. Because the default value of the $WarningPreference variable is Continue, warnings are displayed and execution continues unless you use the WarningAction parameter.

See more here.

Presuppose answered 18/6, 2020 at 22:51 Comment(0)
H
14

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 {}
}

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

Warning stream redirection is only available in PowerShell v3 and newer, though.

Huskey answered 8/6, 2015 at 13:56 Comment(3)
yea, mine accepts pipeline input, check the editted codeDonovan
like this, 1..255 | ForEach-Object {"192.168.1.$_"} | Get-ComputerNameByIPDonovan
Any idea as to why the op is getting a Warning as supposed to an error like I get when running that command?Scrupulous
P
4
$ErrorActionPreference = 'SilentlyContinue'

This global var controls error output of those commands that provide intermittent (non-terminating) errors and warnings. Your error is of this kind, so set preference to silently continue to suppress these warnings.

Plath answered 8/6, 2015 at 13:6 Comment(8)
Anywhere, the begin block seems to be the best place to set, although it'll be better that you would first get its value in the "begin" block, then set it back to original in the "end" block. Also it might be good if you modify your function to accept -errorAction parameter which is listed as common and controls whether the errors of any kind interrupt the process.Plath
still the warning is shown even after putting it in the begin blockDonovan
You need to be careful doing this since it is a preference variable and affects the current powershell session. Not just the scope of the function.Scrupulous
@Scrupulous You can't IIRC change error action preference by a parameter to a .NET function call, so this is probably the only way.Plath
@Donovan Weird, I've tried (from console, not as a function) and setting EAP variable suppressed the exception for me.Plath
I was not sure if this would work for the .net methods either. I just more meant that you should try to set it back once you are done as it is a global change ... not just for this function (pretty sure). It could supress other errors you did not mean to.Scrupulous
@Scrupulous Changes to a preference variable in a function do not affect other scopes unless you use a scope modifier.Huskey
@AnsgarWiechers Nice to see, if so, there is no need to explicitly setting back EAP at the function end. And this makes implementing -errorAction into a simple check if the parameter is set and then change the EAP in begin block.Plath
S
2

You could use a try/catch block for something like this. Consider the following example using a proper formed IP address but had no associated record.

try{
    [System.Net.Dns]::GetHostbyAddress("127.0.0.56")
} Catch [System.Management.Automation.MethodInvocationException]{
    Write-Host "Nothing Record Found"
}

When I tested this the error you were seeing was being caught as [System.Management.Automation.MethodInvocationException] so I checked for that specific error type. Based on it's name I'm sure there are other reasons for it to be called. It is possible to just omit that part altogether and it will catch all errors. Since you account for some other possibilities maybe you don't need it.

If that was a concern you could check the text of the $_.Exception.InnerException to see if it matches the error as well. In the above case it contains the text "The requested name is valid, but no data of the requested type was found".

This might be wrong because I am curious as to why your error is prefixed with "WARNING" where mine is not. A little more research on both our parts might be needed.

Scrupulous answered 8/6, 2015 at 13:32 Comment(1)
let me do some more diggingDonovan
A
0

You can trap the error and force PowerShell to do nothing with it, kind of like a Try/Catch but global for the whole script:

TRAP {"" ;continue} 
[System.Net.Dns]::GetHostbyAddress($IPAddress)
Adman answered 8/6, 2015 at 13:59 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.