SimonS
SimonS

Reputation: 1973

How to ignore Invoke-Webrequest Errormessage

I have a - in my opinion - strange case where PowerShell throws an error, even though I'm trying to ignore it. What's also strange, it's a terminating error, meaning the whole function stops even though it shouldn't

This is my function, which I use to get breached E-Mail Accounts of my company, by using the haveibeenpwned API.

function Get-Pwned {

    Param(
        [Parameter( Mandatory = $true, ValueFromPipeline = $true, Position = 0)]
        [string[]]$EmailAddress,
        [ValidateNotNullOrEmpty()]
        [string]$API = "https://haveibeenpwned.com/api/v2/breachedaccount/"
    )

    Begin { 

        $ErrorActionPreference = "SilentlyContinue"

        # Setzen der Anfrage auf TLS 1.2, da TLS 1.0 nicht akzeptiert wird
        [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

        # ResultArray
        $Pwned = @()
    }

    # über Mail Adressen loopen und schauen ob 
    Process {
        foreach ($Email in $EmailAddress)
        {
            $Uri = "{0}{1}" -f $API, $Email
            Write-Host $Uri
            Invoke-WebRequest $Uri -ea Ignore | select -expand Content | ConvertFrom-Json |
                        foreach { 
                            $Pwned += [PSCustomObject]@{ 
                                Email = $Email
                                Name = $_.Name
                                Domain = $_.Domain
                                BreachDate = $_.BreachDate 
                            }
                        }
        }
    }

    End {
        # Return Object
        $Pwned
    }
}

the Documentation of the API says, that if there's no breach found for an e-mail address, I will get a status code 404 in return.

my Problem is, whenever this happens, i get a completely terminating error. so basically, when an E-Mail Adress isn't pwned (which is good thing), the execution of the script stops completely (which is not a good thing).

as you can see I'm trying to do $ErrorActionPreference = "SilentlyContinue" and -ea Ignore but I still get the error message and my script still stops.

I use the function like this:

Get-Mailbox [email protected] | select -expand EmailAddresses | ? { $_.startswith("smtp:") } | % { $_.split(":")[1] } | Get-Pwned

if you want to test it you can simply do it like this:

"[email protected]", "[email protected]" | get-pwned

That's the error I'm getting:

Invoke-WebRequest : Der Remoteserver hat einen Fehler zurückgegeben: (404) Nicht gefunden. In \server\Powershell-Scripts\Functions\Get-Pwned.ps1:27 Zeichen:13 + Invoke-WebRequest $Uri -ea Ignore | select -expand Conten ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

How can I get my script not to stop when there's an error message, and how can I ignore it, so that i don't get n error message?

Edit: I just noticed, it works if I do it like this:

$addr = "[email protected]", "[email protected]"
Get-Pwned $addr

Why doesn't it work with Pipeline input?

Upvotes: 2

Views: 3571

Answers (1)

Maximilian Burszley
Maximilian Burszley

Reputation: 19694

I can't explain why you're still getting script-terminating errors when setting -ErrorAction, but you can work around this problem by instead wrapping the command in a try/catch block:

try
{
    Invoke-WebRequest -Uri $Uri -ErrorAction Stop |
        Select-Object -ExpandProperty Content | ConvertFrom-Json | ForEach-Object { 
            $Pwned += [pscustomobject]@{ 
                Email = $Email
                Name = $_.Name
                Domain = $_.Domain
                BreachDate = $_.BreachDate 
            }
        }
}
catch
{
    Write-Warning -Message "Error returned! $_"
}

As a footnote, -ErrorAction takes precedence over $ErrorActionPreference.

Upvotes: 1

Related Questions