This script performs several actions using Microsoft Graph and Intune. It identifies encrypted devices missing BitLocker encryption keys, rotates those keys for devices running Windows 10 (version 1909 or higher), and exports the results to a CSV file. Additionally, it manages group memberships by removing old members and adding new ones. Devices missing encryption keys are filtered, and their Azure AD Device IDs are used to update the members of a specific Azure AD group. This helps maintain secure BitLocker management for enrolled devices.
Here is the script:
$GroupId = ''
function Remove-MgGroupMember {
[CmdletBinding()]
param (
$GroupId,
$DirectoryObjectId
)
$request = @{
Uri = "https://graph.microsoft.com/v1.0/groups/$GroupId/members/$DirectoryObjectId/`$ref" ;
Method = 'DELETE'
}
Invoke-MgGraphRequest @request
}
function Update-MgGroupsMembers {
[CmdletBinding()]
param (
$GroupId,
$Members
)
$CurrentGroupMembers = Get-MgGroupMember -GroupId $GroupId | Select-Object -ExpandProperty Id
foreach ($CurrentGroupMember in $CurrentGroupMembers){
if (!($Members | ? {$_ -eq $CurrentGroupMember})) {
Write-Output "Removing $CurrentGroupMember"
Remove-MgGroupMember -GroupId $GroupId -DirectoryObjectId $($CurrentGroupMember)
}
}
foreach ($Member in $Members) {
if (!($CurrentGroupMembers | Where-Object {$_ -EQ $Member})) { #need to fix error already exists
Write-Output "Adding $Member"
New-MgGroupMember -GroupId $GroupId -DirectoryObjectId $Member
}
}
}
Connect-MgGraph -Scopes DeviceManagementManagedDevices.ReadWrite.All,GroupMember.ReadWrite.All, Group.ReadWrite.All, Directory.ReadWrite.All
$NoKeyDevices = Get-IntuneMissingEncriptionKey -Verbose
$NoKeyDevicesEncrypted = $NoKeyDevices | Where-Object IsEncrypted -EQ $true | Where-Object OperatingSystem -EQ 'Windows'
if($NoKeyDevicesEncrypted){
Select-MgProfile -Name beta
Import-Module Microsoft.Graph.DeviceManagement.Actions -Force
#Rotate Bitlocker key for windows 10 1909 and higher
$NoKeyDevicesEncrypted | ForEach-Object {
Invoke-MgRotateDeviceManagementManagedDeviceBitLockerKey -ManagedDeviceId $($_.Id) -Verbose
}
#Export to CSV
$date = (Get-Date).ToString("dd-MM-yyyy")
$path = "$HOME\Desktop\keyreport-$date.csv"
$NoKeyDevicesEncrypted | Export-Csv -NoTypeInformation -Path $path'.csv'
#Add Devices to Group
<# $ObjectIds = @()
foreach($DevId in $($NoKeyDevicesEncrypted.AzureAdDeviceId)){
$ObjectIds += Get-MgDevice -Property Id -Filter "DeviceId eq '$DevId'" | Select-Object -ExpandProperty Id
}
#>
foreach($DevId in $NoKeyDevicesEncrypted.AzureAdDeviceId){ #need to fix limit to 15
if($DevId -eq $NoKeyDevicesEncrypted[0].AzureAdDeviceId){
$Filter = @"
DeviceId eq '$DevId'
"@
continue
}
$Filter += @"
or DeviceId eq '$DevId'
"@
}
$ObjectIds = Get-MgDevice -Property Id -Filter $filter -All | Select-Object -ExpandProperty Id
Update-MgGroupsMembers -GroupId $GroupId -Members $ObjectIds
}