Remove-RoleAssignment.ps1


<#PSScriptInfo
 
.VERSION 1.0
 
.GUID b75da235-c451-4265-a3c3-5a09d57b1175
 
.AUTHOR VIJAY RAAVI
 
.COMPANYNAME Pennywise Solutions
 
.COPYRIGHT
 
.TAGS Remove User from all Resources and its ResourceGroup
 
.LICENSEURI
 
.PROJECTURI
 
.ICONURI
 
.EXTERNALMODULEDEPENDENCIES
 
.REQUIREDSCRIPTS
 
.EXTERNALSCRIPTDEPENDENCIES
 
.RELEASENOTES
 
 
.PRIVATEDATA
 
#>


<#
 
.DESCRIPTION
 To Remove User from all Resources and its Resource Group.
 
#>
 

[cmdletbinding()]
param
(
# Azure AD User ID
[parameter(Mandatory=$true)]
#[ValidateNotNullOrEmpty()]
[string] $SignInName,

# Name of ResourceGroup in which User Should be removed from all its resources
[parameter(Mandatory=$true)]
#[ValidateNotNullOrEmpty()]
[string] $ResourceGroupName,

[parameter(Mandatory=$false)]
[string] $azureRunAsConnectionName = "AzureRunAsConnection"
)

filter timestamp {"[$(Get-Date -Format G)]: $_"}
Write-Output "Remove User Activity started." | timestamp
$VerbosePreference = "Continue"
#$ErrorActionPreference = "Stop" #"SilentlyContinue"
#Authenticate with Azure Automation Run As account (service principal)
$runAsConnectionProfile = Get-AutomationConnection `
-Name $azureRunAsConnectionName
Add-AzureRmAccount -ServicePrincipal `
-TenantId $runAsConnectionProfile.TenantId `
-ApplicationId $runAsConnectionProfile.ApplicationId `
-CertificateThumbprint ` $runAsConnectionProfile.CertificateThumbprint | Out-Null
Write-Output "Authenticated with Automation Run As Account."  | timestamp

    #Set Subscription Context
    $SubscriptionId = (Get-AzureRmContext).Subscription.SubscriptionId 
    #Get List of all resources where User exists in a particular Resource Group
    $roleassignment = Get-AzureRmRoleAssignment -SignInName $SignInName -ResourceGroupName $ResourceGroupName #user@domainname.com
    #$roleassignment| Remove-AzureRmRoleAssignment -ObjectId {$PSItem.ObjectId} -RoleDefinitionName {$PSItem.RoleDefinitionName} -Verbose -WhatIf -Debug
    #$roleassignment | select scope
    #$roleassignment | select scope -Unique
    #Get Unique scope (To a particular resource user can be assigned to multiple roles)
    $roleassignment | select scope -Unique |Get-AzureRmResourceLock -Scope {$_.Scope}
    #Get List of locked resources - To Apply locks at the end of activity
    $Locks=$roleassignment | select scope -Unique |Get-AzureRmResourceLock -Scope {$_.Scope}
  try
    {
   #Get Resource and Resource Group Locks and Remove Locks
   #Remove Resource Group Lock
   $RGLock= Get-AzureRmResourceLock -ResourceGroupName $ResourceGroupName.ToString() -AtScope -ErrorAction SilentlyContinue
    if ($RGLock -eq $null)
    {
        # ResourceGroupLock doesn't exist, No Action to be taken
        Write-Output "Lock @ Resource Group Level doen't exsist"
    }
    else
    {
        # ResourceGroupLock exist, Delete it
        Write-Output "Deleting ResourceGroup Lock"
        #Get-AzureRmResourceLock -ResourceGroupName $ResourceGroupName -AtScope -ErrorAction SilentlyContinue |Remove-AzureRmResourceLock -Force #Not Working in Runbook
        $removeRGLock=Get-AzureRmResourceLock -ResourceGroupName $ResourceGroupName.ToString() -AtScope -ErrorAction SilentlyContinue 
        #Remove-AzureRmResourceLock -ResourceId $removeRGLock.ResourceId -Force #Not Working in Runbook
        Remove-AzureRmResourceLock -LockName $removeRGLock.Name.ToString() -ResourceName $removeRGLock.ResourceName.ToString() -ResourceType Microsoft.Authorization/locks -ResourceGroupName $ResourceGroupName.ToString() -Force

    }

    #Remove locks to all the required resources
    $roleassignment | select scope -Unique |Get-AzureRmResourceLock -Scope {$_.Scope} |Remove-AzureRmResourceLock -Force -Verbose -ErrorAction SilentlyContinue
    #$roleassignment| Remove-AzureRmRoleAssignment -ObjectId {$PSItem.ObjectId} -RoleDefinitionName {$PSItem.RoleDefinitionName} -Verbose -Confirm:$true -WhatIf
    #Remove User Role from all resources
    $roleassignment| Remove-AzureRmRoleAssignment -ObjectId {$PSItem.ObjectId} -RoleDefinitionName {$PSItem.RoleDefinitionName} -Verbose -Confirm:$false -ErrorAction SilentlyContinue
    #Apply Locks
    $locks|New-AzureRmResourceLock -LockName {$PSItem.ResourceName + "-Lock"} -LockLevel CanNotDelete -LockNotes "Delete lock applied from PowerShell" -ResourceName {$PSItem.ResourceName} -ResourceType {$PSItem.ResourceType} -ResourceGroupName {$PSItem.ResourceGroupName} -Force -Verbose
    

    $RGLock= Get-AzureRmResourceLock -ResourceGroupName $ResourceGroupName.ToString() -AtScope -ErrorAction SilentlyContinue
    if ($RGLock -eq $null)
    {
        # ResourceGroupLock doesn't exist, No Action to be taken
        Write-Output "Lock @ Resource Group Level doen't exsist"
       $RGLock= New-AzureRmResourceLock -ResourceGroupName $ResourceGroupName.ToString() -LockName "$ResourceGroupName-Lock" -LockLevel CanNotDelete -LockNotes "$ResourceGroupName Locked from Deleting" -Force
       Write-Output $RGLock
    }
    else
    {
     Write-Output "Lock @ Resource Level already exsist"
    }
   
    # Create Locks for ResourceGroup and Resource
       
      
}
catch #[System.Exception]
{
   Write-Output "check exceptions.."
   Write-Output $_.Exception.Message
}
finally
{
   Write-Output "Finally...Block..."
  if ($RGLock -eq $null)
    {
        # ResourceGroupLock doesn't exist, No Action to be taken
        Write-Output "Lock @ Resource Group Level doen't exsist"
       $RGLock= New-AzureRmResourceLock -ResourceGroupName $ResourceGroupName.ToString() -LockName "$ResourceGroupName-Lock" -LockLevel CanNotDelete -LockNotes "$ResourceGroupName Locked from Deleting" -Force
       Write-Output $RGLock
    }
    else
    {
     Write-Output "Lock @ Resource Level already exsist"
    }
     $locks|New-AzureRmResourceLock -LockName {$PSItem.ResourceName + "-Lock"} -LockLevel CanNotDelete -LockNotes "Delete lock applied from PowerShell" -ResourceName {$PSItem.ResourceName} -ResourceType {$PSItem.ResourceType} -ResourceGroupName {$PSItem.ResourceGroupName} -Force -Verbose
   

}    
filter timestamp {"[$(Get-Date -Format G)]: $_"}
Write-Output "Remove User Activity Ended." | timestamp