Limpiar aplicaciones huérfanas o reemplazadas
Encuentra apps de Intune sin asignaciones o que otra app ya reemplaza (supersedence) y, si lo pides, las elimina del catálogo. Por defecto solo reporta.
Ejemplo en México
Manufactura de autopartes en Querétaro, 120 personas
Después de dos años de pruebas de instaladores, el catálogo de Intune tiene decenas de apps viejas y duplicadas, y el equipo de TI ya no sabe cuáles se usan.
.\cleanup-orphaned-apps.ps1 -OlderThanDays 90 -Remove "true" -WhatIfObtiene la lista de apps sin asignación con más de 90 días y las apps Win32 reemplazadas. Depura primero las claramente abandonadas y deja el resto para revisión.
Cómo implementarlo
- Corre el script sin parámetros para ver el reporte de apps sin asignación y apps reemplazadas (se ignoran las creadas hace menos de 30 días).
- Revisa la lista app por app en la consola de Intune: confirma que nadie la usa como dependencia o la tiene en un plan de despliegue pendiente.
- Repite con -Remove "true" -WhatIf para ver exactamente qué se borraría.
- Cuando estés seguro, corre con -Remove "true" sin -WhatIf; el script pide confirmación por cada app. Guarda el CSV (-ExportToCsv "true") como evidencia de lo que quitaste.
Ver el código completo de cleanup-orphaned-apps.ps1
<#
.TITLE
Cleanup Orphaned Apps
.SYNOPSIS
Finds Intune apps that have no assignments or are superseded by newer versions, and optionally deletes them.
.DESCRIPTION
This script scans the Intune app catalog for cleanup candidates: apps with no
assignments at all, and Win32 apps that a newer app supersedes. Old installer
versions and abandoned test apps accumulate quickly and clutter the catalog. By
default the script only reports; deletion requires the -Remove switch, supports
-WhatIf preview, and prompts per app. Deleting an app from Intune does not
uninstall it from devices that already have it.
.TAGS
Apps,Operational
.MINROLE
Intune Administrator
.PERMISSIONS
DeviceManagementApps.ReadWrite.All
.AUTHOR
Ugur Koc
.VERSION
1.2
.CHANGELOG
1.2 - Added Azure Automation contract validation, portal-safe boolean parameters, beta Graph endpoints, and terminating paging errors
1.1 - Azure Automation now records script progress, outcomes, and summaries in job history
1.0 - Initial release
.LASTUPDATE
2026-07-30
.EXAMPLE
.\cleanup-orphaned-apps.ps1
Reports unassigned and superseded apps without deleting anything
.EXAMPLE
.\cleanup-orphaned-apps.ps1 -OlderThanDays 90
Only reports apps created more than 90 days ago
.EXAMPLE
.\cleanup-orphaned-apps.ps1 -Remove "true" -WhatIf
Shows exactly which apps would be deleted, without deleting them
.NOTES
- Requires Microsoft.Graph.Authentication module
- Superseded means another Win32 app declares a supersedence relationship to this app (supersedingAppCount > 0)
- Deleting an app does not uninstall it from devices; it removes the deployment object
- Recently created apps are excluded by default (-OlderThanDays 30) to avoid flagging work in progress
- Uses beta Graph endpoints because supersedence counts are exposed there
- Local interactive sign-in uses the MgGraphCommunity module to avoid the Graph SDK's mandatory WAM broker on Windows
#>
[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = "High")]
param(
[Parameter(Mandatory = $false, HelpMessage = "Only consider apps created more than this many days ago")]
[ValidateRange(0, 3650)]
[int]$OlderThanDays = 30,
[Parameter(Mandatory = $false, HelpMessage = "Delete the reported apps instead of only reporting")]
[ValidateSet("true", "false", "1", "0", '$true', '$false')]
[string]$Remove,
[Parameter(Mandatory = $false, HelpMessage = "Export results to CSV")]
[ValidateSet("true", "false", "1", "0", '$true', '$false')]
[string]$ExportToCsv,
[Parameter(Mandatory = $false, HelpMessage = "Output path for exports")]
[string]$OutputPath = ".",
[Parameter(Mandatory = $false, HelpMessage = "Force module installation without prompting")]
[ValidateSet("true", "false", "1", "0", '$true', '$false')]
[string]$ForceModuleInstall
)
# Normalize the local module-install override for Azure Automation parameter binding.
$forceModuleInstallRaw = [string]$ForceModuleInstall
Remove-Variable -Name ForceModuleInstall
if ([string]::IsNullOrWhiteSpace($forceModuleInstallRaw)) {
$ForceModuleInstall = $false
}
elseif ($forceModuleInstallRaw.Trim().ToLowerInvariant() -in @("true", "1", '$true')) {
$ForceModuleInstall = $true
}
elseif ($forceModuleInstallRaw.Trim().ToLowerInvariant() -in @("false", "0", '$false')) {
$ForceModuleInstall = $false
}
else {
throw "Parameter 'ForceModuleInstall' accepts only true, false, 1, 0, $true, or $false."
}
# Azure Automation supplies portal parameter values as strings. Normalize the
# public boolean parameters once so local and runbook execution use real booleans.
foreach ($runbookBooleanParameter in @('Remove', 'ExportToCsv')) {
$runbookBooleanRaw = [string](Get-Variable -Name $runbookBooleanParameter -ValueOnly)
Remove-Variable -Name $runbookBooleanParameter
if ([string]::IsNullOrWhiteSpace($runbookBooleanRaw)) {
Set-Variable -Name $runbookBooleanParameter -Value $false
continue
}
switch ($runbookBooleanRaw.Trim().ToLowerInvariant()) {
{ $_ -in @("true", "1", '$true') } {
Set-Variable -Name $runbookBooleanParameter -Value $true
}
{ $_ -in @("false", "0", '$false') } {
Set-Variable -Name $runbookBooleanParameter -Value $false
}
default {
throw "Parameter '$runbookBooleanParameter' accepts only true, false, 1, 0, $true, or $false."
}
}
}
# ============================================================================
# ENVIRONMENT DETECTION AND SETUP
# ============================================================================
function Initialize-RequiredModule {
param(
[string[]]$ModuleNames,
[bool]$IsAutomationEnvironment,
[bool]$ForceInstall = $false
)
foreach ($ModuleName in $ModuleNames) {
Write-Verbose "Checking module: $ModuleName"
$module = Get-Module -ListAvailable -Name $ModuleName | Select-Object -First 1
if (-not $module) {
if ($IsAutomationEnvironment) {
throw "Module '$ModuleName' is not available in Azure Automation"
}
else {
Write-Information "Module '$ModuleName' not found. Installing..." -InformationAction Continue
if (-not $ForceInstall) {
$response = Read-Host "Install module '$ModuleName'? (Y/N)"
if ($response -notmatch '^[Yy]') {
throw "Module '$ModuleName' is required but installation was declined."
}
}
try {
$isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")
$scope = if ($isAdmin) { "AllUsers" } else { "CurrentUser" }
Install-Module -Name $ModuleName -Scope $scope -Force -AllowClobber -Repository PSGallery
Write-Information "✓ Successfully installed '$ModuleName'" -InformationAction Continue
}
catch {
throw "Failed to install module '$ModuleName': $($_.Exception.Message)"
}
}
}
Import-Module -Name $ModuleName -Force -ErrorAction Stop
}
}
# Detect execution environment
$IsAzureAutomation = $null -ne $PSPrivateMetadata.JobId.Guid
# Initialize required modules
$RequiredModules = @("Microsoft.Graph.Authentication")
# MgGraphCommunity gives WAM-free interactive sign-in for local runs
if (-not $IsAzureAutomation) {
$RequiredModules += "MgGraphCommunity"
}
try {
Initialize-RequiredModule -ModuleNames $RequiredModules -IsAutomationEnvironment $IsAzureAutomation -ForceInstall $ForceModuleInstall
Write-Verbose "✓ All required modules are available"
}
catch {
Write-Error "Module initialization failed: $_"
exit 1
}
# ============================================================================
# AUTHENTICATION
# ============================================================================
try {
if ($IsAzureAutomation) {
Write-Output "Connecting to Microsoft Graph using Managed Identity..."
Connect-MgGraph -Identity -NoWelcome -ErrorAction Stop
}
else {
Write-Output "Connecting to Microsoft Graph..."
$Scopes = @(
"DeviceManagementApps.ReadWrite.All"
)
Connect-MgGraphCommunity -Scopes $Scopes -NoWelcome -ErrorAction Stop
}
Write-Output "✓ Successfully connected to Microsoft Graph"
}
catch {
Write-Error "Failed to connect to Microsoft Graph: $($_.Exception.Message)"
exit 1
}
# ============================================================================
# HELPER FUNCTIONS
# ============================================================================
function Get-MgGraphAllPage {
param(
[string]$Uri,
[int]$DelayMs = 100
)
$allResults = @()
$nextLink = $Uri
do {
try {
if ($allResults.Count -gt 0) {
Start-Sleep -Milliseconds $DelayMs
}
$response = Invoke-MgGraphRequest -Uri $nextLink -Method GET
if ($null -ne $response.value) {
$allResults += $response.value
}
else {
$allResults += $response
}
$nextLink = $response.'@odata.nextLink'
}
catch {
if ($_.Exception.Message -like "*429*") {
Write-Information "Rate limit hit, waiting 60 seconds..." -InformationAction Continue
Start-Sleep -Seconds 60
continue
}
throw "Error fetching data: $($_.Exception.Message)"
}
} while ($nextLink)
return $allResults
}
# ============================================================================
# MAIN SCRIPT LOGIC
# ============================================================================
try {
Write-Output "Retrieving app catalog with assignments..."
$apps = Get-MgGraphAllPage -Uri "https://graph.microsoft.com/beta/deviceAppManagement/mobileApps?`$expand=assignments"
Write-Output "✓ Found $(@($apps).Count) apps"
$cutoffDate = (Get-Date).AddDays(-$OlderThanDays)
[System.Collections.Generic.List[Object]]$report = @()
$deleted = 0
$deleteFailed = 0
foreach ($app in $apps) {
$created = if ($app.createdDateTime) { [DateTime]::Parse($app.createdDateTime.ToString()) } else { $null }
# Recently created apps are probably still being set up
if ($created -and $created -gt $cutoffDate) {
continue
}
$isUnassigned = (@($app.assignments).Count -eq 0)
$isSuperseded = ([int]$app.supersedingAppCount -gt 0)
if (-not $isUnassigned -and -not $isSuperseded) {
continue
}
$reason = if ($isUnassigned -and $isSuperseded) { "Unassigned + Superseded" }
elseif ($isSuperseded) { "Superseded" }
else { "Unassigned" }
$appType = ([string]$app.'@odata.type') -replace "#microsoft.graph.", ""
$action = "Reported"
if ($Remove) {
if ($PSCmdlet.ShouldProcess("$($app.displayName) ($appType, $reason)", "Delete Intune app")) {
try {
Invoke-MgGraphRequest -Uri "https://graph.microsoft.com/beta/deviceAppManagement/mobileApps/$($app.id)" -Method DELETE
Write-Output "✓ Deleted: $($app.displayName)"
$action = "Deleted"
$deleted++
}
catch {
Write-Warning "Failed to delete '$($app.displayName)': $($_.Exception.Message)"
$action = "DeleteFailed"
$deleteFailed++
}
}
else {
$action = "Skipped"
}
}
$report.Add([PSCustomObject]@{
AppName = $app.displayName
AppType = $appType
Publisher = $app.publisher
Reason = $reason
Created = if ($created) { $created.ToString("yyyy-MM-dd") } else { "" }
Superseded = $isSuperseded
AppId = $app.id
Action = $action
})
}
# ----- Display results -----
Write-Output "`nORPHANED APP REPORT"
Write-Output ("=" * 50)
Write-Output "Age filter: created more than $OlderThanDays days ago"
Write-Output "Generated: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')"
Write-Output ("=" * 50)
if ($report.Count -eq 0) {
Write-Output "`nNo orphaned or superseded apps found."
}
else {
foreach ($reasonGroup in ($report | Group-Object -Property Reason | Sort-Object Name)) {
Write-Output "`n$($reasonGroup.Name) ($($reasonGroup.Count) apps)"
foreach ($row in ($reasonGroup.Group | Sort-Object AppName)) {
Write-Output " $($row.AppName) [$($row.AppType)] created $($row.Created) - $($row.Action)"
}
}
}
# Summary
Write-Output "`n"
Write-Output ("=" * 50)
Write-Output "Summary: $($report.Count) cleanup candidates of $(@($apps).Count) total apps"
if ($Remove) {
Write-Output "Deleted: $deleted | Failed: $deleteFailed"
}
elseif ($report.Count -gt 0) {
Write-Output "Run again with -Remove to delete (add -WhatIf for a dry run). Deleting does NOT uninstall from devices."
}
Write-Output ("=" * 50)
# Export to CSV if requested
if ($ExportToCsv) {
$timestamp = Get-Date -Format "yyyy-MM-dd_HH-mm-ss"
$csvPath = Join-Path $OutputPath "Orphaned_Apps_$timestamp.csv"
$report | Export-Csv -Path $csvPath -NoTypeInformation -Encoding UTF8
Write-Output "✓ CSV report saved: $csvPath"
}
}
catch {
Write-Error "Script execution failed: $($_.Exception.Message)"
exit 1
}
finally {
try {
$null = Disconnect-MgGraph
Write-Output "✓ Disconnected from Microsoft Graph"
}
catch {
Write-Verbose "Graph disconnection completed"
}
}
# Copia sin cambios de https://github.com/ugurkocde/IntuneAutomation (commit 797bb2e).
# MIT License
#
# Copyright (c) 2025 Ugur Koc | Microsoft MVP
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.