Saltar al contenido
Microsoft scripts

Scripts de Intune

Licencias VPP de Apple

Muestra el uso de licencias de apps VPP de iOS y macOS y avisa de las que están cerca de agotarse y de los tokens VPP por vencer.

Antes de correrloUsa endpoints beta. Un token VPP vencido detiene las instalaciones sin avisar; no esperes al error del usuario.

Ejemplo en México

Universidad privada en Toluca, 800 personas

Se acerca el inicio de semestre y se asignarán 300 iPads a alumnos nuevos; compras necesita saber qué licencias alcanzan.

.\get-vpp-license-report.ps1 -WarningThresholdPercent 85 -TokenExpiryWarningDays 45 -ExportToCsv "true"

Una tabla con licencias usadas y totales por app. TI pide a compras más licencias de dos apps y renueva un token que vence en tres semanas.

Cómo implementarlo

  1. Ejecuta el script; si no tienes VPP configurado, no verás tokens ni apps.
  2. Ajusta los umbrales con -WarningThresholdPercent y -TokenExpiryWarningDays según tu proceso de compra.
  3. Revisa las apps marcadas por utilización alta y los tokens con fecha de vencimiento cercana.
  4. Compra más licencias o renueva el token en Apple Business Manager antes de que los usuarios vean errores de instalación.
Ver el código completo de get-vpp-license-report.ps1
<#
.TITLE
    Get VPP License Report

.SYNOPSIS
    Reports Apple VPP app license utilization and flags apps and tokens that are close to exhaustion or expiry.

.DESCRIPTION
    This script reads all Apple Volume Purchase Program tokens and VPP apps (iOS and
    macOS) from Intune and reports used versus total licenses per app, highlighting
    apps above a configurable utilization threshold. VPP token state and expiration
    are included because an expired token silently breaks app installs. Use it to
    buy licenses before users hit "installation failed" and to catch tokens that
    need renewal.

.TAGS
    Apps,Reporting

.MINROLE
    Intune Administrator

.PERMISSIONS
    DeviceManagementApps.Read.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
    .\get-vpp-license-report.ps1
    Reports all VPP apps with their license utilization

.EXAMPLE
    .\get-vpp-license-report.ps1 -WarningThresholdPercent 80
    Flags apps that have used 80 percent or more of their licenses

.EXAMPLE
    .\get-vpp-license-report.ps1 -ExportToCsv "true"
    Exports the license report to a timestamped CSV file

.NOTES
    - Requires Microsoft.Graph.Authentication module
    - Tenants without Apple VPP (Apps and Books) configured will report no tokens and no apps
    - License counts come from the iosVppApp and macOsVppApp usedLicenseCount / totalLicenseCount properties
    - Uses beta Graph endpoints because VPP app license properties are exposed there
    - Local interactive sign-in uses the MgGraphCommunity module to avoid the Graph SDK's mandatory WAM broker on Windows
#>

[CmdletBinding()]
param(
    [Parameter(Mandatory = $false, HelpMessage = "Utilization percentage above which an app is flagged")]
    [ValidateRange(1, 100)]
    [int]$WarningThresholdPercent = 90,

    [Parameter(Mandatory = $false, HelpMessage = "Days before token expiry to flag a VPP token")]
    [ValidateRange(1, 365)]
    [int]$TokenExpiryWarningDays = 30,

    [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 @('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.Read.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 {
    # ----- VPP tokens -----
    Write-Output "Retrieving VPP tokens..."
    $tokens = Get-MgGraphAllPage -Uri "https://graph.microsoft.com/beta/deviceAppManagement/vppTokens"
    Write-Output "✓ Found $(@($tokens).Count) VPP token(s)"

    # ----- VPP apps (iOS and macOS) -----
    Write-Output "Retrieving VPP apps..."
    $iosVppApps = Get-MgGraphAllPage -Uri "https://graph.microsoft.com/beta/deviceAppManagement/mobileApps?`$filter=isof('microsoft.graph.iosVppApp')"
    $macVppApps = Get-MgGraphAllPage -Uri "https://graph.microsoft.com/beta/deviceAppManagement/mobileApps?`$filter=isof('microsoft.graph.macOsVppApp')"
    $vppApps = @($iosVppApps) + @($macVppApps)
    Write-Output "✓ Found $(@($vppApps).Count) VPP app(s)"

    if (@($tokens).Count -eq 0 -and @($vppApps).Count -eq 0) {
        Write-Output "`nNo Apple VPP tokens or apps found - is Apple Apps and Books configured for this tenant?"
        return
    }

    [System.Collections.Generic.List[Object]]$report = @()
    foreach ($app in $vppApps) {
        $total = [int]$app.totalLicenseCount
        $used = [int]$app.usedLicenseCount
        $utilization = if ($total -gt 0) { [math]::Round(($used / $total) * 100, 1) } else { 0 }

        $status = if ($total -eq 0) { "NoLicenses" }
        elseif ($utilization -ge 100) { "Exhausted" }
        elseif ($utilization -ge $WarningThresholdPercent) { "NearLimit" }
        else { "OK" }

        $platform = if ($app.'@odata.type' -like "*macOsVppApp") { "macOS" } else { "iOS" }

        $report.Add([PSCustomObject]@{
                AppName       = $app.displayName
                Platform      = $platform
                TokenAppleId  = $app.vppTokenAppleId
                UsedLicenses  = $used
                TotalLicenses = $total
                UtilizationPct = $utilization
                Status        = $status
                AppId         = $app.id
            })
    }

    # ----- Display results -----
    Write-Output "`nVPP LICENSE REPORT"
    Write-Output ("=" * 50)
    Write-Output "Warning threshold: $WarningThresholdPercent% | Generated: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')"
    Write-Output ("=" * 50)

    # Token health first - expired tokens break everything downstream
    if (@($tokens).Count -gt 0) {
        Write-Output "`nVPP tokens:"
        foreach ($token in $tokens) {
            $expiry = if ($token.expirationDateTime) { [DateTime]::Parse($token.expirationDateTime.ToString()) } else { $null }
            $daysLeft = if ($expiry) { [math]::Round(($expiry - (Get-Date)).TotalDays, 0) } else { $null }

            $tokenLine = "  $($token.appleId) | state: $($token.state)"
            if ($null -ne $daysLeft) {
                $tokenLine += " | expires in $daysLeft days"
            }
            Write-Output $tokenLine

            if ($token.state -ne "valid") {
                Write-Warning "  Token '$($token.appleId)' state is '$($token.state)' - VPP app installs may be failing"
            }
            elseif ($null -ne $daysLeft -and $daysLeft -le $TokenExpiryWarningDays) {
                Write-Warning "  Token '$($token.appleId)' expires in $daysLeft days - renew it in Apple Business Manager"
            }
        }
    }

    if ($report.Count -gt 0) {
        foreach ($statusGroup in ($report | Group-Object -Property Status | Sort-Object Name)) {
            Write-Output "`n[$($statusGroup.Name)] $($statusGroup.Count) app(s)"
            foreach ($row in ($statusGroup.Group | Sort-Object UtilizationPct -Descending)) {
                Write-Output "  $($row.AppName) ($($row.Platform)): $($row.UsedLicenses)/$($row.TotalLicenses) licenses ($($row.UtilizationPct)%)"
            }
        }
    }

    # Summary
    $flagged = @($report | Where-Object { $_.Status -in @("NearLimit", "Exhausted") })
    Write-Output "`n"
    Write-Output ("=" * 50)
    Write-Output "Summary: $($report.Count) VPP apps, $($flagged.Count) at or above $WarningThresholdPercent% utilization"
    Write-Output ("=" * 50)

    # Export to CSV if requested
    if ($ExportToCsv) {
        $timestamp = Get-Date -Format "yyyy-MM-dd_HH-mm-ss"
        $csvPath = Join-Path $OutputPath "VPP_License_Report_$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.

Relacionados