Import-AadAzureRoleAssignments.ps1

function Import-AadAzureRoleAssignments {
# Ensure you are signed in to Az Account (Connect-AzAccount)
# Ensure you are signed in to AzureAD (Connect-AzureAD)

# $ImportCSV : Location of CSV file for role assignments
# $SubId : Azure subscription ID to re-apply permissions to
  param (
    [string]$ImportCsv, [string]$SubId
  )

    # REQUIRE AadSupport Session
    RequireConnectAadSupport
    # END REGION
  
  # Make the param -ImportCsv required and import the CSV
  # This is assuming the CSV was exported from Get-AzureRmRoleAssignment
  if(-not($ImportCsv)) { Throw "You must supply a value for -ImportCsv" }
  if(-not($SubId)) { Throw "You must supply a value for -SubId" }

  $HaveAccess = 0
  try {
    Set-AzContext -SubscriptionId $SubId | Out-Null
    $HaveAccess = $True
  } Catch {
    $HaveAccess = $False
    Write-Host "$SubId does not exist or You don't have access to it" -ForegroundColor Red
  }

  If ($HaveAccess) {
      $roles = Import-CSV $ImportCsv
  
      # Start assigning roles
      foreach ($role in $roles) {
        write-host "--- STARTING NEW ROLE ASSIGNMENT ---"
        $RoleDisplayName = $role.DisplayName
        $RoleObjectId = $role.ObjectId
        $RoleScope = $role.scope
        $RoleSignInName = $role.SignInName
        $RoleDefId = $role.RoleDefinitionId
        if ($role.Scope -ne "/") { # Skip Azure AD scope assignments as it is not possible to assign to this scope
      
          # Group Role Assignment
          if ($role.ObjectType -eq "Group") {
            $group = Get-AzAdGroup -SearchString $role.DisplayName
            if ($group.count -eq 1) {
              $GroupId = $group.id
              write-host "New-AzRoleAssignment -scope $rolescope -ObjectId $GroupId -RoleDefinitionId $RoleDefId -verbose"
              New-AzRoleAssignment -scope $rolescope -ObjectId $GroupId -RoleDefinitionId $RoleDefId -verbose
            } 
            elseif ($group.count -gt 1) { 
              write-Host "Could not assign Access Control to Group $roleDisplayName" -ForegroundColor Yellow
              write-Host "Multiple groups exist with the same DisplayName; unable to identify which group to assign Access Control" -ForegroundColor Yellow
            } 
            else { 
              write-Host "Could not assign Access Control to Group $roleDisplayName" -ForegroundColor Yellow
              write-Host "No groups exist with that name" -ForegroundColor Yellow
            }
          } 

          # User Role Assignment
          elseif ($role.ObjectType -eq "User") {
            $InitialDomain = (Get-AzureADDomain | where {$_.IsInitial -eq $true}).Name
            $isExternal = $false # User is external and SignInName has underscore to be replaced by @
        
            #Modify SignInName if external user
            $i = $role.SignInName.indexOf("#EXT#")
            if ($i -eq -1) { $i = $role.SignInName.length }
            else {
              $isExternal = $true
            }
            $role.SignInName = $role.SignInName.Substring(0,$i)

            if ($isExternal -eq $true) {
              $ati = $role.SignInName.lastindexOf("_")
              $part1 = $role.SignInName.Substring(0,$ati)
              $part2 = $role.SignInName.Substring(($ati+1))
              $role.SignInName = $part1 + "@" + $part2
            }

            # Look for UPN suffix
            $ati = $role.SignInName.indexOf("@")
            $suffix = $role.SignInName.Substring(($ati+1))

            # Check if user domain is verified, If not then this user is still external user
            $DomainExists = (Get-AzureAdDomain | where {$suffix -match $_.Name}).Count
            if (!$DomainExists) {
                $role.SignInName = $role.SignInName.Replace("@","_")
                $role.SignInName = $role.SignInName + "#EXT#@" + $InitialDomain
            }

            $SignInName = $role.SignInName
            $user = Get-AzADUser -UserPrincipalName $role.SignInName
            $UserObjectId = $user.Id

            if ($role.RoleDisplayName -eq "CoAdministrator") {
              $rolescope = "/subscriptions/$subid"
              $RoleDefId = "8e3af657-a8ff-443c-a75c-2fe8c4bcb635"
            }

            if ($user.count -eq 1) {
              write-host "New-AzureRmRoleAssignment -scope $rolescope -ObjectId $userObjectId -RoleDefinitionId $RoleDefId -verbose"
              New-AzRoleAssignment -scope $rolescope -ObjectId $userObjectId -RoleDefinitionId $RoleDefId -verbose
            } elseif ($user.count -eq 0) {
              write-Host "Could not assign Access Control to User $roleSignInName" -ForegroundColor Yellow
              write-Host "User does not exist or can not be found!"  -ForegroundColor Yellow
            }
          } elseif ($role.ObjectType -match "ServicePrincipal") {
              write-host "You will have to manually apply RBAC for service principals: ObjectId: $RoleObjectId" -ForegroundColor Yellow
          } 
        } else { write-host "Assigning to scope '/' level not allowed" -ForegroundColor Yellow}
      }
  }
}