Can we remove the shared permission from one drive for a deleted user in one drive
# Define Azure AD App Credentials
$tenantId = "
$clientId = "
$clientSecret = "
$scope = "https://graph.microsoft.com/.default"
# CSV file paths
$ownersCsv = "D:\Owners.csv"
$usersCsv = "D:\UsersToRemove.csv"
$logFilePath = "D:\Removed_Permissions_Log.csv"
# Read OneDrive owners from CSV
$owners = Import-Csv -Path $ownersCsv
if (-not $owners -or -not $owners.Email) {
Write-Host "❌ Error: Owners.csv is empty or missing the 'Email' column!"
Exit
}
# Read users to remove from CSV
$usersToRemove = Import-Csv -Path $usersCsv | Select-Object -ExpandProperty Email
if (-not $usersToRemove) {
Write-Host "❌ Error: UsersToRemove.csv is empty or missing the 'Email' column!"
Exit
}
Write-Host "✅ Users to Remove: $($usersToRemove -join ', ')"
# Initialize log file if not present
if (-Not (Test-Path $logFilePath)) {
"DateTime, File/Folder Name, Item ID, Removed User, Permission ID" | Out-File -FilePath $logFilePath -Encoding UTF8
}
# Get Access Token
$body = @{
client_id = $clientId
scope = $scope
client_secret = $clientSecret
grant_type = "client_credentials"
}
$tokenResponse = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token" -Method Post -ContentType "application/x-www-form-urlencoded" -Body $body
$accessToken = $tokenResponse.access_token
$headers = @{ Authorization = "Bearer $accessToken" }
# Function to remove permissions and log details
function Remove-Permissions($userEmail, $item) {
$permissionsUrl = "https://graph.microsoft.com/v1.0/users/$userEmail/drive/items/$($item.id)/permissions"
Write-Host "🔍 Checking permissions for: $($item.name) [$($item.id)]"
try {
$permissions = Invoke-RestMethod -Uri $permissionsUrl -Headers $headers -Method Get
Write-Host "🔹 Found $($permissions.value.Count) permissions."
foreach ($perm in $permissions.value) {
$removePermission = $false
$sharedUserEmail = ""
# Check for direct user permissions
if ($perm.grantedTo -and $perm.grantedTo.user.email -in $usersToRemove) {
$removePermission = $true
$sharedUserEmail = $perm.grantedTo.user.email
}
# Check for multiple shared identities
elseif ($perm.grantedToIdentities) {
$matchingUsers = $perm.grantedToIdentities | Where-Object { $_.user.email -in $usersToRemove }
if ($matchingUsers) {
$removePermission = $true
$sharedUserEmail = $matchingUsers.user.email
}
}
# Remove permission if found
if ($removePermission -and $sharedUserEmail -ne "") {
Write-Host "❌ Removing access for $sharedUserEmail on $($item.name) [$($perm.id)]"
$removePermissionUrl = "https://graph.microsoft.com/v1.0/users/$userEmail/drive/items/$($item.id)/permissions/$($perm.id)"
Invoke-RestMethod -Uri $removePermissionUrl -Headers $headers -Method Delete -ErrorAction Stop
# Log removal
$logEntry = "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss'), $($item.name), $($item.id), $sharedUserEmail, $($perm.id)"
Add-Content -Path $logFilePath -Value $logEntry
}
}
} catch {
Write-Host "⚠️ Error removing permissions: $_"
}
}
# Function to recursively process OneDrive items
function Process-DriveItems($userEmail, $folderId) {
$driveItemsUrl = "https://graph.microsoft.com/v1.0/users/$userEmail/drive/items/$folderId/children"
try {
$driveItems = Invoke-RestMethod -Uri $driveItemsUrl -Headers $headers -Method Get
foreach ($item in $driveItems.value) {
Write-Host "📂 Scanning: $($item.name)"
# Remove permissions for this item
Remove-Permissions -userEmail $userEmail -item $item
# If item is a folder, recurse into it
if ($item.folder -ne $null) {
Process-DriveItems -userEmail $userEmail -folderId $item.id
}
}
} catch {
Write-Host "⚠️ Error accessing OneDrive items: $_"
}
}
# Process each OneDrive owner in Owners.csv
foreach ($user in $owners) {
$userEmail = $user.Email
Write-Host "📂 Processing OneDrive for: $userEmail"
try {
# Get the root folder ID
$rootInfo = Invoke-RestMethod -Uri "https://graph.microsoft.com/v1.0/users/$userEmail/drive/root" -Headers $headers -Method Get
$rootId = $rootInfo.id
Write-Host "🔍 Scanning OneDrive Root for: $userEmail (Root ID: $rootId)"
Process-DriveItems -userEmail $userEmail -folderId $rootId
} catch {
Write-Host "❌ Error: Unable to access OneDrive for $userEmail. Skipping..."
}
}
Write-Host "✅ Finished processing all users!"
Write-Host "📜 Log file saved at: $logFilePath"
this is my code to remove user from shared files. But using this code i am un able to remove the permission of a deleted user because i cant get the UPN or user mail or user id. Is there any way to remove the shared permission of a deleted user.