Functions/Get-IntuneDeviceManagementScriptsAssignmentReport.ps1


function Get-IntuneDeviceManagementScriptsAssignmentReport {
    [CmdletBinding()]
    param (
        # [Parameter(Mandatory)] [string] $ParameterName
    )

    # $Configs = Get-IntuneDeviceConfigurationPolicy
    $Scripts = (Invoke-GraphRequest -Uri "https://graph.microsoft.com/beta/deviceManagement/deviceManagementScripts").value


    $ScriptAssignments = @()
    $i = 0
    foreach ($s in $Scripts) {
        $i++
        if ($Scripts.count) {
            # Write-Progress -Activity "Processing Scripts" -CurrentOperation "$($s.displayName) ($($i) / $($Scripts.count))" -PercentComplete ( ($i / ($Scripts.count) * 100) )
        }
        (Invoke-GraphRequest -Uri "https://graph.microsoft.com/beta/deviceManagement/deviceManagementScripts/$($s.id)/assignments").value | ForEach-Object {
            $Properties = [ordered]@{
                ScriptId = $s.id
                type     = $_.target.'@odata.type'
                AadGroup = $_.target.groupId
            }
            $ScriptAssignments += New-Object -TypeName psobject -Property $Properties
        }
    }


    $AadGroups = @()
    $ScriptAssignments.AadGroup | Select-Object -Unique | ForEach-Object {
        # try {
        # $AadGroups += Get-AzureADGroup -ObjectId $_ -ea 0
        $AadGroups += Get-MgGroup -GroupId $_ -ea 0
        # }
        # catch { }
    }
    $AadGroups = $AadGroups | Sort-Object DisplayName



    $Output = @()
    $i = 0

    foreach ($s in $Scripts) {

        $Properties = [ordered]@{
            ScriptName = $s.displayName
            ScriptId   = $s.id
            AllUsers   = $null
            AllDevices = $null
        }

        foreach ($ag in $AadGroups) {
            $Properties.Add($ag.DisplayName, $null)
        }

        $ScriptAssignment = $ScriptAssignments | Where-Object ScriptId -EQ $s.id


        foreach ($sa in $ScriptAssignment) {

            if ($sa.AadGroup) {

                if ($sa.type -eq "#microsoft.graph.exclusionGroupAssignmentTarget") {
                    $AssignmentType = "excluded"
                } elseif ($sa.type -eq "#microsoft.graph.groupAssignmentTarget") {
                    $AssignmentType = "included"
                }

                $TargetGroup = $AadGroups | Where-Object Id -EQ $sa.AadGroup
                if ($TargetGroup) {
                    $Properties[$TargetGroup.DisplayName] = $AssignmentType
                }

            } else {
                if ($sa.type -eq "#microsoft.graph.allLicensedUsersAssignmentTarget") {
                    $Properties["AllUsers"] = "included"
                }
                if ($sa.type -eq "#microsoft.graph.allDevicesAssignmentTarget") {
                    $Properties["AllDevices"] = "included"
                }
            }

        }

        $Output += New-Object -TypeName psobject -Property $Properties

    }

    $Output = $Output | Sort-Object ScriptName

    return $Output


}