windowspowershelltry-catchexchange-serverpowershell-ise

Powershell Try/catch - get-user


I'm learning posh. And I'm trying to understand why this script doesn't catch the warning.

try{
    get-user aaaa -WarningAction Stop
}
catch
{
    Write-Host "hi"
}

Here is the error:

get-user : The operation couldn't be performed because object 'aaaa' couldn't be found on
'iDC01.contoso.com'. At C:\Users\Gra***\Desktop\test.ps1:2 char:5
+     get-user aaaa -WarningAction Stop
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Get-User], ManagementObjectNotFoundException
    + FullyQualifiedErrorId : [Server=ME1,RequestId=ebcde0d2-9222-443b-b25a-ef7279fd168e,
      TimeStamp=20.06.2017 13:51:35] [FailureCategory=Cmdlet-ManagementObjectNotFoundException]
      FE0D594D,Microsoft.Exchange.Management.RecipientTasks.GetUser

I've tryied -WarningActions Stop and -ErrorAction Stop but no results.

In general I've understood the basics of try/catch and the following script works ok.

try{
Get-Process -name xyz -ErrorAction Stop
}
catch{
Write-Host "oops"
}

I'm using powershell_ise 5.1. Do you know what's wrong with the get-user? Also, I can't use Get-ADuser.


Solution

  • There are two things that can be caught when calling a function, Error or Warning. You can set these with the $WarningPreference or $ErrorActionPreference globally in the script, or individually by using the -ea or -wa arguments. In your example, I'd use the following to be sure:

    Try {
        Get-User aaaa -wa Stop -ea Stop
    } Catch {
        Write-Output "hi"
        Write "[$($_.Exception.GetType().FullName)] - $($_.Exception.Message)"
    }
    

    about_Preference_Variables