Functions/New-MultipleIntuneAppAssignments.ps1


function New-MultipleIntuneAppAssignments {
    [CmdletBinding()]
    param (
        [Parameter()] [string[]] $AppIds,
        [Parameter()] [string] $OS,
        [Parameter()] [string] $GroupName,
        [Parameter()] [ValidateSet("required", "uninstall", "UnassignAll", "available", "availableWithoutEnrollment")] [string] $Intent
    )



    $AllApps = (Invoke-GraphRequest -Uri "https://graph.microsoft.com/beta/deviceAppManagement/mobileApps").value
    $AllApps = $AllApps | Where-Object { ($_."@odata.type" -ne "#microsoft.graph.managedIOSStoreApp") -and ($_."@odata.type" -ne "#microsoft.graph.managedAndroidStoreApp") }



    if ($AppIds) {
        $SelectedApps = @()
        foreach ($id in $AppIds) {
            if ($AllApps.id -contains $id) {
                $SelectedApps += $AllApps | Where-Object id -eq $id
            }
        }
    } else {
        $SelectedApps = $AllApps | Select-Object '@odata.type', id, displayName, publisher | Out-GridView -OutputMode Multiple -Title "Select Apps"
    }

    if (!($SelectedApps)) { break }

    #$SelectedApps | Format-Table

    if ($GroupName) {
        $AADGroup = Get-MgGroup -Filter "(displayname eq '$($GroupName)')"
    } else {
        $AADGroup = Get-MgGroup -All | Sort-Object DisplayName | Out-GridView -OutputMode Single -Title "Select AAD Group"
    }
    if (!($AADGroup)) { break }
    $target = New-DeviceAndAppManagementAssignmentTargetObject -groupAssignmentTarget -groupId $AADGroup.ObjectId

    if (!($Intent)) {
        $Intent = "required", "uninstall", "UnassignAll", "available", "availableWithoutEnrollment" | Out-GridView -OutputMode Single -Title "Select Intent"
        if (!($Intent)) {
            break
        }
    }


    foreach ($a in $SelectedApps) {

        $Assignments = Get-IntuneMobileAppAssignment -mobileAppId $a.id

        $Assignments | ForEach-Object {
            if ($_.target.groupId -eq $AADGroup.ObjectId) {
                Write-Output "Removing previous assignment for app: `"$($a.displayName)`" ($($_.mobileAppId)), group `"$($AADGroup.displayName)`" ($($_.target.groupId)), intent: $($_.Intent)"
                Remove-IntuneMobileAppAssignment -mobileAppId $a.id -mobileAppAssignmentId $_.mobileAppAssignmentId
            }
        }

        if ($Intent -ne "UnassignAll") {
            Write-Output "Assigning app: `"$($a.displayName)`" ($($a.id)), group `"$($AADGroup.displayName)`" ($($AADGroup.objectId)), intent: $($Intent)"
            New-IntuneMobileAppAssignment -mobileAppId $a.id -intent $Intent -target $target -ea 0 | Out-Null
        }

    }
    Write-Output "$($SelectedApps.id -join ",")"
}


#New-MultipleIntuneAppAssignments -GroupName "Intune Jaap" -Intent required