functions/roleManagement/roleAssignments/Invoke-AzurePIMroleAssignment.ps1

function Invoke-AzurePIMroleAssignment {
    [CmdletBinding()]
    Param (
        [string[]] $SpecificResources,
        [System.Management.Automation.PSCmdlet]
        $Cmdlet = $PSCmdlet
    )
        
    
    begin
    {
        $resourceName = "roleAssignments"
        if (!$script:desiredConfiguration[$resourceName]) {
            Stop-PSFFunction -String "AzurePIM.NoDefinitions" -StringValues "roleAssignment"
            return
        }
        Test-AzureConnection
        $secureStringToken = (Get-AzAccessToken -AsSecureString -ResourceUrl $script:apiBaseUrl).Token
        $azureToken = [System.Net.NetworkCredential]::new('', $secureStringToken).Password
    }

    process {
        if (Test-PSFFunctionInterrupt) { return }
        $testResults = Test-AzurePIMroleAssignment -Cmdlet $Cmdlet

        foreach ($result in $testResults) {
            Beautify-AzurePIMTestResult -TestResult $result -FunctionName $MyInvocation.MyCommand
            switch ($result.ActionType) {
                "Create" {
                    try {
                        $requestMethod = "PUT"
                        $subscriptionId = Resolve-Subscription -InputReference $result.DesiredConfiguration.subscriptionReference
                        switch ($result.DesiredConfiguration.scopeType) {
                            "subscription" {$scopeId = $subscriptionId}
                            "resourceGroup" {$scopeId = Resolve-ResourceGroup -InputReference $result.DesiredConfiguration.scopeReference -SubscriptionId $subscriptionId}
                            "resource" {$scopeId = $subscriptionId + $result.DesiredConfiguration.scopeReference}
                        }
                        switch ($result.DesiredConfiguration.principalType) {
                            "group" {
                                $principalId = Resolve-Group -InputReference $result.DesiredConfiguration.principalReference
                            }
                            "user" {
                                $principalId = Resolve-User -InputReference $result.DesiredConfiguration.principalReference
                            }
                        }
                        $roleDefinitionId = Resolve-AzureRoleDefinition -InputReference $result.DesiredConfiguration.roleReference -SubscriptionId $subscriptionId
                        switch ($result.DesiredConfiguration.expirationType) {
                            "noExpiration" {
                                $requestBody = @{
                                    "properties"= @{
                                        "principalId" = $principalId
                                        "roleDefinitionId" = $roleDefinitionId
                                        "requestType" = "AdminAssign"
                                        "scheduleInfo" = @{
                                            "startDateTime" = $result.DesiredConfiguration.startDateTime
                                            "expiration" = @{
                                                "type" = "noExpiration"
                                            }
                                        }
                                    }
                                }
                            }
                            "AfterDateTime" {
                                $requestBody = @{
                                    "properties"= @{
                                        "principalId" = $principalId
                                        "roleDefinitionId" = $roleDefinitionId
                                        "requestType" = "AdminAssign"
                                        "scheduleInfo" = @{
                                            "startDateTime" = $result.DesiredConfiguration.startDateTime
                                            "expiration" = @{
                                                "type" = "AfterDateTime"
                                                "endDateTime" = $result.DesiredConfiguration.endDateTime
                                            }
                                        }
                                    }
                                }
                            }
                            "AfterDuration" {
                                $requestBody = @{
                                    "properties"= @{
                                        "principalId" = $principalId
                                        "roleDefinitionId" = $roleDefinitionId
                                        "requestType" = "AdminAssign"
                                        "scheduleInfo" = @{
                                            "startDateTime" = $result.DesiredConfiguration.startDateTime
                                            "expiration" = @{
                                                "type" = "AfterDuration"
                                                "duration" = $result.DesiredConfiguration.duration
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        $guid = (New-Guid).Guid
                        $requestBody = $requestBody | ConvertTo-Json -Depth 5
                        switch ($result.DesiredConfiguration.type) {
                            "eligible" {
                                Invoke-RestMethod -Method $requestMethod -Uri "$($script:apiBaseUrl)$($scopeId.trimStart("/"))/providers/Microsoft.Authorization/roleEligibilityScheduleRequests/$($guid)?api-version=2020-10-01-preview" -Headers @{"Authorization"="Bearer $($azureToken)"} -Body $requestBody -ContentType "application/json"  | Out-Null
                            }
                            "active" {
                                $requestBody = @{
                                    "properties"= @{
                                        "principalId" = $principalId
                                        "roleDefinitionId" = $roleDefinitionId
                                    }
                                }
                                $requestBody = $requestBody | ConvertTo-Json -Depth 5
                                Invoke-RestMethod -Method $requestMethod -Uri "$($script:apiBaseUrl)$($scopeId.trimStart("/"))/providers/Microsoft.Authorization/roleAssignments/$($guid)?api-version=2018-01-01-preview" -Headers @{"Authorization"="Bearer $($azureToken)"} -Body $requestBody -ContentType "application/json"  | Out-Null
                            }
                        }
                        Write-PSFMessage -Level Host -String "AzurePIM.Invoke.ActionCompleted" -StringValues $result.Tenant, $result.ResourceType, $result.ResourceName, (Get-ActionColor -Action $result.ActionType), $result.ActionType
                    }
                    catch {
                        Write-PSFMessage -Level Error -String "AzurePIM.Invoke.ActionFailed" -StringValues $result.Tenant, $result.ResourceType, $result.ResourceName, $result.ActionType
                        throw $_
                    }
                 }
                "Update" {
                    try {
                        $requestMethod = "PUT"
                        switch ($result.DesiredConfiguration.principalType) {
                            "group" {
                                $principalId = Resolve-Group -InputReference $result.DesiredConfiguration.principalReference
                            }
                            "user" {
                                $principalId = Resolve-User -InputReference $result.DesiredConfiguration.principalReference
                            }
                        }
                        $subscriptionId = Resolve-Subscription -InputReference $result.DesiredConfiguration.subscriptionReference
                        $roleDefinitionId = Resolve-AzureRoleDefinition -InputReference $result.DesiredConfiguration.roleReference -SubscriptionId $subscriptionId.trimStart("/")
                        switch ($result.DesiredConfiguration.expirationType) {
                            "noExpiration" {
                                $requestBody = @{
                                    "properties"= @{
                                        "principalId" = $principalId
                                        "roleDefinitionId" = $roleDefinitionId
                                        "requestType" = "AdminUpdate"
                                        "scheduleInfo" = @{
                                            "startDateTime" = $result.DesiredConfiguration.startDateTime
                                            "expiration" = @{
                                                "endDateTime" = $null
                                                "type" = "noExpiration"
                                            }
                                        }
                                    }
                                }
                            }
                            "AfterDateTime" {
                                $requestBody = @{
                                    "properties"= @{
                                        "principalId" = $principalId
                                        "roleDefinitionId" = $roleDefinitionId
                                        "requestType" = "AdminUpdate"
                                        "scheduleInfo" = @{
                                            "startDateTime" = $result.DesiredConfiguration.startDateTime
                                            "expiration" = @{
                                                "type" = "AfterDateTime"
                                                "endDateTime" = $result.DesiredConfiguration.endDateTime
                                            }
                                        }
                                    }
                                }
                            }
                            "AfterDuration" {
                                $requestBody = @{
                                    "properties"= @{
                                        "principalId" = $principalId
                                        "roleDefinitionId" = $roleDefinitionId
                                        "requestType" = "AdminUpdate"
                                        "scheduleInfo" = @{
                                            "startDateTime" = $result.DesiredConfiguration.startDateTime
                                            "expiration" = @{
                                                "type" = "AfterDuration"
                                                "duration" = $result.DesiredConfiguration.duration
                                                "endDateTIme" = $null
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        
                        $requestBody = $requestBody | ConvertTo-Json -Depth 5
                        $guid = (New-Guid).Guid
                        switch ($result.DesiredConfiguration.type) {
                            "eligible" {
                                Invoke-RestMethod -Method $requestMethod -Uri "$($script:apiBaseUrl)$($result.AzureResource.properties.scope.trimStart("/"))/providers/Microsoft.Authorization/roleEligibilityScheduleRequests/$($guid)?api-version=2020-10-01-preview" -Headers @{"Authorization"="Bearer $($azureToken)"} -Body $requestBody -ContentType "application/json"  | Out-Null
                            }
                            "active" {
                                Invoke-RestMethod -Method $requestMethod -Uri "$($script:apiBaseUrl)$($result.AzureResource.properties.scope.trimStart("/"))/providers/Microsoft.Authorization/roleAssignmentScheduleRequests/$($guid)?api-version=2020-10-01-preview" -Headers @{"Authorization"="Bearer $($azureToken)"} -Body $requestBody -ContentType "application/json"  | Out-Null
                            }
                        }
                        Write-PSFMessage -Level Host -String "AzurePIM.Invoke.ActionCompleted" -StringValues $result.Tenant, $result.ResourceType, $result.ResourceName, (Get-ActionColor -Action $result.ActionType), $result.ActionType
                    }
                    catch {
                        Write-PSFMessage -Level Error -String "AzurePIM.Invoke.ActionFailed" -StringValues $result.Tenant, $result.ResourceType, $result.ResourceName, $result.ActionType
                        throw $_
                    }
                }
                "Delete" {
                    $requestMethod = "PUT"
                    switch ($result.DesiredConfiguration.principalType) {
                        "group" {
                            $principalId = Resolve-Group -InputReference $result.DesiredConfiguration.principalReference
                        }
                        "user" {
                            $principalId = Resolve-User -InputReference $result.DesiredConfiguration.principalReference
                        }
                    }
                    $subscriptionId = Resolve-Subscription -InputReference $result.DesiredConfiguration.subscriptionReference
                    $roleDefinitionId = Resolve-AzureRoleDefinition -InputReference $result.DesiredConfiguration.roleReference -SubscriptionId $subscriptionId.trimStart("/")
                    try {

                        $requestBody = @{
                            "properties" = @{
                                "principalId" = $principalId
                                "roleDefinitionId" = $roleDefinitionId
                                "requestType" = "AdminRemove"
                            }
                        }

                        $requestBody = $requestBody | ConvertTo-Json -Depth 5
                        $guid = (New-Guid).Guid
                        switch ($result.DesiredConfiguration.type) {
                            "eligible" {
                                Invoke-RestMethod -Method $requestMethod -Uri "$($script:apiBaseUrl)$($result.AzureResource.properties.scope.trimStart("/"))/providers/Microsoft.Authorization/roleEligibilityScheduleRequests/$($guid)?api-version=2020-10-01-preview" -Headers @{"Authorization" = "Bearer $($azureToken)"} -Body $requestBody -ContentType "application/json" | Out-Null
                            }
                            "active" {
                                $requestMethod = "DELETE"
                                Invoke-RestMethod -Method $requestMethod -Uri "$($script:apiBaseUrl)$($result.AzureResource.id.trimStart("/"))?api-version=2018-01-01-preview" -Headers @{"Authorization" = "Bearer $($azureToken)"}  | Out-Null
                            }
                        }
                        Write-PSFMessage -Level Host -String "AzurePIM.Invoke.ActionCompleted" -StringValues $result.Tenant, $result.ResourceType, $result.ResourceName, (Get-ActionColor -Action $result.ActionType), $result.ActionType                        
                    }
                    catch {
                        Write-PSFMessage -Level Error -String "AzurePIM.Invoke.ActionFailed" -StringValues $result.Tenant, $result.ResourceType, $result.ResourceName, $result.ActionType
                        throw $_
                    }

                }
                "NoActionRequired" {}
                default {
                    Write-PSFMessage -Level Warning -String "AzurePIM.Invoke.ActionTypeUnknown" -StringValues $result.ActionType
                }        
            }
        }
    }
}