powershellpowershell-4.0skypeskype-for-business

Try Catch Not Working for Get-CsUser Command


I have setup a Try Catch block to check if a Skype user exists or not and the command throws an error but the Catch block does not catch it and display the proper error message.

Here is the code followed by the error message that it throws in Windows PowerShell ISE

try
{
    $Output = Get-CsUser -Identity "Chrlis.domain\$username"

} Catch
{
    If($error[0] -like "*Management object not found for identity*") {
        Write-Host "SKYPE LYNC ERROR3: $username does not have a Skype account" -ForegroundColor Red
    } Else {
        Write-Host "SKYPE LYNC ERROR4:" $Error[0].Exception -ForegroundColor Red
    }
}

Management object not found for identity "Chrlis.domain\Jacob.Hal".
    + CategoryInfo          : InvalidData: (Chrlis.domain\Jacob.Hal:UserIdParameter) [Get-CsUser], ManagementException
    + FullyQualifiedErrorId : Identity,Microsoft.Rtc.Management.AD.Cmdlets.GetOcsUserCmdlet
    + PSComputerName        : pigeon1.Chrlis.domain

Any help would be greatly appreciated.


Solution

  • You could modify the -erroractionpreference Param to silently continue and then do a .count() or .length() check to see if there is actually anything in the variable and action appropriately.

    I would provide Boiler-plate Code but it's a bit hard on mobile.

    Have a read through Ed's post on it -- https://devblogs.microsoft.com/scripting/hey-scripting-guy-how-can-i-use-erroractionpreference-to-control-cmdlet-handling-of-errors/