To modify the script to loop through all access packages and remove the specified user from each of them, you can query all the access packages first, then loop through each package and perform the removal operation if the user has an assignment. Here’s an updated version of the script:
Script to Remove a User from All Access PackagesScript to Remove a User from All Access Packages
Connect to Microsoft Graph API with the necessary scopes
Connect-MgGraph -Scopes "EntitlementManagement.ReadWrite.All"
Specify the user ID you want to remove from all access packages
$userId = "11bb11bb-cc22-dd33-ee44-55ff55ff55ff"
Retrieve all Access Packages
$accessPackages = Get-MgEntitlementManagementAccessPackage -All -ErrorAction Stop
foreach ($accessPackage in $accessPackages) {
# Get the Access Package ID
$accessPackageId = $accessPackage.Id
# Filter for any assignment where the user has been assigned this package and it's in 'Delivered' state
$filter = "accessPackage/Id eq '" + $accessPackageId + "' and state eq 'Delivered' and target/objectId eq '" + $userId + "'"
$assignment = Get-MgEntitlementManagementAssignment -Filter $filter -ExpandProperty target -All -ErrorAction Stop
# If there's an active assignment, proceed with removal
if ($assignment -ne $null) {
$params = @{
requestType = "adminRemove"
assignment = @{ id = $assignment.id }
}
# Request to remove the assignment
New-MgEntitlementManagementAssignmentRequest -BodyParameter $params
Write-Host "Removed user from Access Package: $($accessPackage.DisplayName)"
} else {
Write-Host "No active assignment found for user in Access Package: $($accessPackage.DisplayName)"
}
}
Disconnect from Microsoft Graph API
Disconnect-MgGraph
Breakdown of Changes:
1. Get All Access Packages:
• Get-MgEntitlementManagementAccessPackage -All retrieves all available access packages.
2. Loop Through Each Access Package:
• The script loops through each access package ($accessPackages) to check if the specified user ($userId) has an active assignment in the package.
3. Check for Active Assignment:
• For each access package, it filters the assignment by checking the state ('Delivered') and the objectId of the user.
4. Remove Assignment:
• If the user has an assignment in the access package, the script constructs the removal request (adminRemove) and executes it using New-MgEntitlementManagementAssignmentRequest.
5. Logging:
• The script logs either the removal of the user from the access package or indicates that no active assignment was found.
Things to Ensure:
• Make sure you have the necessary Microsoft Graph API permissions (EntitlementManagement.ReadWrite.All) to perform these operations.
• You should also have administrative privileges in the Azure AD tenant to manage access packages and assignments.
This modified script will remove the specified user from all access packages they are currently assigned to.
If my answer is helpful to you, you can adopt it, thank you!