How to capture Error like Get-AzRoleAssignment : Operation returned an invalid status code 'NotFound' and do some activity in if-else block based on this error

Rituparna Hazra (Digital) 20 Reputation points
2024-09-20T11:32:46.0666667+00:00

How to capture Error like Get-AzRoleAssignment : Operation returned an invalid status code 'NotFound' and do some activity in if-else block based on this error

Azure Role-based access control
Azure Role-based access control
An Azure service that provides fine-grained access management for Azure resources, enabling you to grant users only the rights they need to perform their jobs.
804 questions
Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,517 questions
Microsoft Entra ID
Microsoft Entra ID
A Microsoft Entra identity service that provides identity management and access control capabilities. Replaces Azure Active Directory.
21,585 questions
0 comments No comments
{count} votes

Accepted answer
  1. Marcin Policht 23,160 Reputation points MVP
    2024-09-20T11:41:43.31+00:00

    Use the following:

    try {
        # Attempt to get a role assignment
        $roleAssignment = Get-AzRoleAssignment -ObjectId "your-object-id" -RoleDefinitionName "Contributor"
        
        # If the command succeeds, perform some action
        Write-Output "Role assignment found."
        
        # Do some activity if role assignment is found
        # For example: Write-Output "Role assignment details: $roleAssignment"
        
    } catch {
        # Check if the error message contains 'NotFound'
        if ($_.Exception.Message -match "NotFound") {
            Write-Output "Role assignment not found. Performing alternate activity."
            
            # Perform alternate activity here
            # For example: Write-Output "Creating new role assignment..."
            
        } else {
            # Handle other types of errors
            Write-Output "An unexpected error occurred: $($_.Exception.Message)"
        }
    }
    
    

    If the above response helps answer your question, remember to "Accept Answer" so that others in the community facing similar issues can easily find the solution. Your contribution is highly appreciated.

    hth

    Marcin


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.