An app registration gets a secret, the project goes to production, and the credential stays in the directory with the right to read mailboxes, with nobody left to answer for it. This article builds a scheduled sweep in Microsoft Graph PowerShell: inventory, owners, expiring or unused credentials, rotation with overlap, then disabling before deletion. You will also learn what App Instance Lock and app management policies change for your scripts.
Application object and service principal: the targeting mistake that costs dearly
A service principal is the local identity your tenant issues so that an application is authorized in it; its global template is the application object. The Microsoft Learn documentation sums up the relationship this way: the application object is the global representation across all tenants, and the service principal is the local representation for a given tenant.
A multi-tenant application has a single application object in its home tenant and a separate service principal in each tenant that has consented. A secret created on the application object therefore authenticates somewhere other than where you think you cleaned up. Cleaning up the wrong object leaves the credential active.
Three practical consequences for the script:
- secrets and certificates used for application authentication are managed on the application object (its
Id, not the service principal's); - the containment switch,
AccountEnabled, is on the service principal; - Microsoft recommends running a service with the credential defined on the application object rather than on the service principal (Microsoft Learn documentation on the
servicePrincipalKeyExpiryrecommendation).
Vendors publish machine-to-human ratios (144 to 1 at Entro Security in its H1 2025 report, 109 to 1 in CyberArk's 2026 report). These are their own telemetry: measure your tenant before sizing the effort. The same caution applies to the figure that only 3% of the permissions granted to workload identities are used over a year (Microsoft's 2024 multicloud security report). The behavior it describes is real: a script that breaks for lack of permission opens a ticket within the hour, whereas a permission granted "just in case" never opens one.
What changes in 2026 for your scripts
Two developments change how you write a sweep.
March 31, 2026
End of authentication without a service principal
Microsoft had asked customers to act before this date: Entra ID blocks authentication of non-Microsoft multi-tenant applications that have no service principal in the authenticating tenant. The inventory in this guide also serves as the list of impacted applications.
June 2026
App Instance Lock enabled by default
According to Our Cloud Network, Microsoft enables App Instance Lock by default on all new applications, with a rollout announced from early to late June 2026. Existing applications are not affected.
A change blocked by the lock returns a 400 Bad Request error. A script that adds a credential to the service principal of a multi-tenant application can therefore fail.
The lock does not erase what already exists
As Michev explains, enabling the App Instance Property Lock does not remove local credentials already added to a service principal, and they keep working. A cleanup is still needed. He also points to a beta property, enforcementScope (for example foreignTenantOnly), which limits the lock to foreign tenants: in the home tenant, authorized users can still modify credentials.
App management policies (defaultAppManagementPolicy or custom policies) block the addition of secrets or limit the lifetime of secrets and certificates, on applications as well as on service principals. A custom policy assigned to an application replaces the default policy, and exemptions exist through custom security attributes (Microsoft Learn). They can make a rotation fail if the new credential exceeds the permitted lifetime: your script must therefore read the policy before choosing an EndDateTime.
Prerequisites and minimum Graph permissions
Run the sweep under a dedicated automation identity, not under an administrator account. Start read-only, and add the write scopes at the time of rotation.
| Task | Minimum Graph permission | What it opens |
|---|---|---|
| Inventory of applications and service principals | Application.Read.All (Directory.Read.All also covers it, with more privileges) | Get-MgApplication, Get-MgServicePrincipal |
| Reading owners | Application.Read.All | Get-MgServicePrincipalOwner and the application owners endpoint |
| Adding or removing credentials | Application.ReadWrite.All, or Application.ReadWrite.OwnedBy in app-only mode on owned objects | addPassword, removePassword, addKey, removeKey |
| Disabling or deleting | Application.ReadWrite.All | accountEnabled and service principal deletion |
| Unused credential findings | DirectoryRecommendations.Read.All | Entra recommendations engine |
| Activity history | AuditLog.Read.All | Service principal sign-ins and audit events |
For a read-only audit, the first three read rows plus AuditLog.Read.All and DirectoryRecommendations.Read.All are enough. The recommendations API is served by the Graph beta endpoint (/beta/directory/recommendations); the Reports Reader, Security Reader and Global Reader roles give read-only access (Microsoft Learn).
Before running the first sweep
- PowerShell 7.4 or later with the Microsoft.Graph module (tested with version 2.19.0); the Az.KeyVault module for rotation.
- No use of the retired AzureAD and MSOnline modules.
- A machine identity for the scheduled run: system-assigned managed identity of an Azure Automation account, or a service principal with a certificate.
- An Azure Key Vault and write access for the identity performing the rotation.
- A Microsoft Entra ID P1 or P2 license to download sign-in logs via the Graph API.
Workload ID Premium for unused credentials
The staleAppCreds recommendation ("Remove unused credentials from apps") is still in preview at the time of writing. Its sample response indicates requiredLicenses = microsoftEntraWorkloadId, hence a Workload ID Premium license (Microsoft Learn). App Governance alerts (Defender for Cloud Apps) are also reserved for Workload ID Premium customers according to Thomas Naunheim, but his article dates from 2023: recheck the licenses. Without the license, record the capability as unavailable in the report rather than showing zero.
Implementation
The pipeline writes one artifact per step: a late failure never destroys earlier evidence. The scripts below share the variables $Apps, $Sps and $ReportPath, and run in the same session.
Step 1: connect with the smallest set of scopes
Confirm the identity and tenant the session actually carries: a session inherited from an old connection can point to another directory and skew every count without an error.
1Install-Module Microsoft.Graph -Scope CurrentUser -MinimumVersion 2.19.02Connect-MgGraph -Scopes 'Application.Read.All','AuditLog.Read.All','DirectoryRecommendations.Read.All'3Get-MgContext | Select-Object Account, TenantId, ScopesExpected output: the account, the tenant ID and the list of granted scopes. If a scope is missing, the first call that needs it returns a 403.
Step 2: inventory and spot objects without owners
Collect the two collections with the properties the following steps read, then write them to disk. The $count operator in a filter is an advanced query: it requires -ConsistencyLevel eventual and -CountVariable. Single quotes prevent PowerShell from interpreting $count before it is sent.
1$ReportPath = Join-Path $PWD 'sp-sweep'2New-Item -ItemType Directory -Path $ReportPath -Force | Out-Null3 4# Both collections, with the governance properties5$Apps = Get-MgApplication -All -Property Id,AppId,DisplayName,CreatedDateTime,PasswordCredentials,KeyCredentials6$Sps = Get-MgServicePrincipal -All -Property Id,AppId,DisplayName,AccountEnabled,ServicePrincipalType,ApplicationTemplateId,PasswordCredentials,KeyCredentials7 8$Apps | Select-Object DisplayName, AppId, Id, CreatedDateTime |9 Export-Csv -Path (Join-Path $ReportPath 'apps.csv') -NoTypeInformation10$Sps | Select-Object DisplayName, AppId, Id, ServicePrincipalType, AccountEnabled, ApplicationTemplateId |11 Export-Csv -Path (Join-Path $ReportPath 'serviceprincipals.csv') -NoTypeInformation12 13# Objects without owners (advanced query)14[array]$OwnerlessApps = Get-MgApplication -All -Property DisplayName,Id,AppId,CreatedDateTime `15 -Filter 'owners/$count eq 0' -CountVariable OwnerCount -ConsistencyLevel eventual16[array]$OwnerlessSps = Get-MgServicePrincipal -All -Property DisplayName,Id,AppId `17 -Filter 'owners/$count eq 0' -CountVariable SpOwnerCount -ConsistencyLevel eventual18 19$OwnerlessApps | Select-Object DisplayName, AppId, Id |20 Export-Csv -Path (Join-Path $ReportPath 'ownerless-apps.csv') -NoTypeInformation21$OwnerlessSps | Select-Object DisplayName, AppId, Id |22 Export-Csv -Path (Join-Path $ReportPath 'ownerless-sps.csv') -NoTypeInformationApplicationTemplateId identifies a service principal created from an application template; it is null otherwise. Remove these rows from the remediation queue and address them to the vendor. Two owners per application is the minimum that survives a resignation; one of the two should be a group. If the advanced query times out on a large tenant, fall back to a Get-MgServicePrincipalOwner loop per object, scheduled overnight: it issues one Graph request per service principal.
To check the privileges actually held, not just requested, application role assignments (Get-MgServicePrincipalAppRoleAssignment) remain the right source: they include grants that never went through a consent screen.
Step 3: detect dormancy in sign-in logs
Service principal sign-ins form a distinct class of logs. The signIn resource in v1.0 carries no service principal field: read the servicePrincipalSignInActivities report instead, exposed in beta.
1$Since = (Get-Date).AddDays(-90)2 3# Paged walk through the activity report4$Rows = @()5$Uri = 'https://graph.microsoft.com/beta/reports/servicePrincipalSignInActivities'6while ($Uri) {7 $Page = Invoke-MgGraphRequest -Method GET -Uri $Uri8 $Rows += $Page.value9 $Uri = $Page.'@odata.nextLink'10}11 12# Index by appId: keep the most recent date across the activity streams13$LastSeenByAppId = @{}14foreach ($Row in $Rows) {15 $Timestamps = @(16 $Row.lastSignInActivity.lastSignInDateTime17 $Row.lastSignInActivity.lastNonInteractiveSignInDateTime18 $Row.lastSignInActivity.lastSuccessfulSignInDateTime19 $Row.applicationAuthenticationClientSignInActivity.lastSignInDateTime20 $Row.applicationAuthenticationClientSignInActivity.lastNonInteractiveSignInDateTime21 $Row.applicationAuthenticationClientSignInActivity.lastSuccessfulSignInDateTime22 $Row.delegatedClientSignInActivity.lastSignInDateTime23 $Row.delegatedClientSignInActivity.lastNonInteractiveSignInDateTime24 $Row.delegatedClientSignInActivity.lastSuccessfulSignInDateTime25 ) | Where-Object { $_ } | ForEach-Object { [datetime]$_ }26 $LastSeenByAppId[$Row.appId] = ($Timestamps | Sort-Object -Descending | Select-Object -First 1)27}28 29$DormantSps = $Sps | Where-Object {30 $_.ServicePrincipalType -eq 'Application' -and31 (-not $LastSeenByAppId.ContainsKey($_.AppId) -or $LastSeenByAppId[$_.AppId] -lt $Since)32}33$DormantSps | Select-Object DisplayName, AppId, Id |34 Export-Csv -Path (Join-Path $ReportPath 'dormant-principals.csv') -NoTypeInformationLoading the whole report into memory suits a small tenant. At scale, send the service principal sign-in logs to a Log Analytics workspace: otherwise, your dormancy window shrinks to the default retention.
Step 4: separate expiring credentials from unused credentials
An expiration date is a calendar fact read from the object; a credential that is no longer used is a telemetry fact that only the recommendations engine provides. The two call for different actions.
1$Threshold = (Get-Date).AddDays(60)2$Now = Get-Date3 4$Expiring = foreach ($App in $Apps) {5 foreach ($Cred in (@($App.PasswordCredentials) + @($App.KeyCredentials))) {6 $Bucket = $null7 # Test for null first: $null -le [datetime] is $true in PowerShell8 if ($null -eq $Cred.EndDateTime) { $Bucket = 'NeverExpires' }9 elseif ($Cred.EndDateTime -lt $Now) { $Bucket = 'Expired' }10 elseif ($Cred.EndDateTime -le $Threshold) { $Bucket = 'Expiring' }11 12 if ($Bucket) {13 $Days = $null14 if ($Cred.EndDateTime) { $Days = [int]($Cred.EndDateTime - $Now).TotalDays }15 [PSCustomObject]@{16 ObjectType = 'Application'17 DisplayName = $App.DisplayName18 ObjectId = $App.Id19 CredentialName = $Cred.DisplayName20 KeyId = $Cred.KeyId21 EndDateTime = $Cred.EndDateTime22 Bucket = $Bucket23 DaysRemaining = $Days24 }25 }26 }27}28$Expiring | Export-Csv -Path (Join-Path $ReportPath 'expiring-credentials.csv') -NoTypeInformationThe NeverExpires bucket is the most severe. It must be separated from Expiring, otherwise a credential with no end of life gets an absurd number of days.
For usage telemetry, query the recommendations beta endpoint and export the impacted resources of staleAppCreds.
1$Recos = (Invoke-MgGraphRequest -Method GET -Uri 'https://graph.microsoft.com/beta/directory/recommendations').value2$Stale = @($Recos | Where-Object { $_.recommendationType -eq 'staleAppCreds' })3 4if ($Stale.Count -eq 0) {5 Write-Warning 'staleAppCreds recommendation absent: check license or availability. Credential dormancy: unavailable.'6}7foreach ($Reco in $Stale) {8 $ImpactedUri = 'https://graph.microsoft.com/beta/directory/recommendations/{0}/impactedResources' -f $Reco.id9 $Impacted = Invoke-MgGraphRequest -Method GET -Uri $ImpactedUri10 $Impacted | ConvertTo-Json -Depth 6 |11 Set-Content -Path (Join-Path $ReportPath 'stale-credentials.json')12}Two reading rules. A credential is considered unused if it has not been used for 30 days, and already expired credentials do not appear in the list of impacted resources. An expired secret that nothing uses belongs to the cleanup backlog; a live, unused credential calls for a revocation decision, to be approved by its owner. The servicePrincipalKeyExpiry recommendation, also in preview, triggers for service principal credentials that expire within 30 days.
Step 5: rotate a secret without downtime
Rotation is first a sequencing problem. A swap in the wrong order breaks the workload and makes the team wary of credential hygiene.
Generate the replacement
Create the new secret on the application object, using its Id from the inventory. The wrong identifier returns a 404 that looks like a permission defect.
Store it in Key Vault immediately
The Microsoft Learn documentation for addPassword is explicit: the password cannot be retrieved afterwards. The secret text exists only in that response.
Switch the consumer and verify
Update the client application, run its workload once and check the KeyId used in the sign-in log.
Remove the old secret
Both secrets are valid during the overlap: keep it short, otherwise you recreate the sprawl the rotation was meant to solve.
The following script covers steps 1, 2 and 4 with a dry-run mode. Key Vault secret names accept only letters, digits and hyphens, hence the name cleanup.
1# Prerequisites: Az.KeyVault, connected Az session (Connect-AzAccount), Application.ReadWrite.All scope2$DryRun = $true3$AppObjectId = '<application-object-id>'4$VaultName = '<key-vault-name>'5 6$App = Get-MgApplication -ApplicationId $AppObjectId7$PreviousKeyId = $App.PasswordCredentials |8 Sort-Object EndDateTime | Select-Object -First 1 -ExpandProperty KeyId9$SecretName = (($App.DisplayName -replace '[^0-9a-zA-Z-]', '-') -replace '-{2,}', '-').Trim('-')10 11if ($DryRun) {12 Write-Host ('Dry run: a secret would be added to {0}, then {1} would be removed.' -f $App.DisplayName, $PreviousKeyId)13}14else {15 # Lifetime: align with the app management policy in force16 $NewSecret = Add-MgApplicationPassword -ApplicationId $AppObjectId -PasswordCredential @{17 DisplayName = ('Rotated ' + (Get-Date -Format 'yyyyMMdd'))18 EndDateTime = (Get-Date).AddMonths(6)19 }20 Set-AzKeyVaultSecret -VaultName $VaultName -Name ($SecretName + '-client-secret') `21 -SecretValue (ConvertTo-SecureString $NewSecret.SecretText -AsPlainText -Force) | Out-Null22 Write-Host ('New KeyId {0}, expires {1}' -f $NewSecret.KeyId, $NewSecret.EndDateTime)23 24 # Run only after the consumer has been validated:25 # Remove-MgApplicationPassword -ApplicationId $AppObjectId -KeyId $PreviousKeyId26}The removal stays commented out: it must follow the sign-in log check, not the same script pass. Use the same sequence for a certificate, because a one-step replacement carries the same risk of downtime. Microsoft recommends using a managed identity as the credential whenever possible, failing that certificates rather than passwords, renewing often, not sharing a credential between applications and limiting the number per application (Microsoft Learn).
Step 6: disable before deleting
Deletion is the only irreversible step: it follows a disabled period that preserves the ability to investigate.
1$DryRun = $true2$SpId = '<service-principal-object-id>'3 4if ($DryRun) {5 Write-Host ('Dry run: service principal {0} would be disabled.' -f $SpId)6}7else {8 Update-MgServicePrincipal -ServicePrincipalId $SpId -AccountEnabled:$false9}10 11# Read back to confirm12Get-MgServicePrincipal -ServicePrincipalId $SpId | Select-Object DisplayName, AccountEnabledExpected output after a non-dry run: AccountEnabled set to False. Leave the identity disabled for a full reporting cycle: a service principal that nobody complains about after 30 days of being blocked is a service principal nobody needs.
Permanent deletion: no way back
Remove-MgServicePrincipal and the credential-removal cmdlets modify the tenant. Entra ID restores a deleted app registration with its service principal during the 30-day soft-delete window; permanent deletion from deleted items is the action nothing can undo. Test on a test application first.
Step 7: schedule without storing a secret
A system-assigned managed identity on an Azure Automation account gives the runbook a service principal without a client secret. Grant it only the read application roles; add Application.ReadWrite.All only on the day rotation is automated.
1# Prerequisite: account authorized to assign application roles2Connect-MgGraph -Scopes 'AppRoleAssignment.ReadWrite.All','Application.Read.All'3 4$MiPrincipalId = '<automation-account-managed-identity-principal-id>'5$GraphSp = Get-MgServicePrincipal -Filter 'appId eq ''00000003-0000-0000-c000-000000000000'''6 7foreach ($Permission in 'Application.Read.All','AuditLog.Read.All','DirectoryRecommendations.Read.All') {8 $RoleId = ($GraphSp.AppRoles |9 Where-Object { $_.Value -eq $Permission -and $_.AllowedMemberTypes -contains 'Application' }).Id10 11 New-MgServicePrincipalAppRoleAssignedTo -ServicePrincipalId $GraphSp.Id -BodyParameter @{12 PrincipalId = $MiPrincipalId13 ResourceId = $GraphSp.Id14 AppRoleId = $RoleId15 }16}Then import Microsoft.Graph.Authentication and the submodules you call from the Automation module gallery, matching the runbook's runtime environment, and attach a schedule: nightly inventory, weekly notification.
For alerting, the audit log names the events to watch: addition or removal of service principal credentials (the strongest signal in case of an unexpected entry), Add app role assignment to service principal, Add owner to application and Remove owner from service principal. Route the Entra diagnostic settings to Log Analytics and query the AuditLogs table on ActivityDisplayName and InitiatedBy.
Troubleshooting: six common symptoms
| Symptom | Likely cause | Resolution |
|---|---|---|
| Syntax error or empty result on the owners/$count filter | Dollar sign interpreted by PowerShell, or ConsistencyLevel eventual missing | Filter in single quotes, with -ConsistencyLevel eventual and -CountVariable |
| 404 during rotation | Service principal ID used instead of the application object ID | Use the Id from Get-MgApplication |
| 403 on a Graph call | Missing scope on the session or the managed identity | Compare with the permissions table and reconnect the session |
| 400 Bad Request when adding a credential | App Instance Lock active, or app management policy (maximum lifetime exceeded) | Check the lock and the assigned policy, shorten the new credential lifetime |
| No staleAppCreds recommendation | Preview not available, license missing, or credentials already expired (excluded) | Check the Workload ID Premium license; record the capability as unavailable |
| Secret name rejected by Key Vault | Characters other than letters, digits and hyphens | Clean the display name before Set-AzKeyVaultSecret |
Preventing the return of sprawl
The sweep cleans up, but prevents nothing. Put the two-owner rule in the change process that creates the registration, and make the nightly report visible to the team that owns the workload. Then enforce by policy the maximum lifetime of secrets and certificates, or the blocking of secrets, with app management policies.
To go further on application identity governance, see our guide to securing application identities with Microsoft Entra, and our analysis of limiting Application Administrator privileges per application. To control who can query Graph with the SDK, see access control for the Graph PowerShell SDK.
Frequently asked questions
Do you need a paid license for this pipeline?
Inventory, owners, rotation and disabling rely on Microsoft Graph permissions in any Entra ID tenant. Downloading sign-in logs via the Graph API requires an Entra ID P1 or P2 license. Detection of unused credentials (staleAppCreds) indicates a Workload ID Premium license in the Microsoft Learn sample response.
What is the difference between an expiring credential and an unused credential?
An expiring credential has an EndDateTime within your alert window: it is a maintenance task with a deadline. An unused credential has not been used for 30 days according to the recommendations engine: it is a revocation decision that the owner must approve.
Can you delete all service principals without owners?
No, not without checking sign-in activity: ownerless objects and dead identities are populations that overlap only partially. Disable the object, wait a cycle and check that no workload breaks. An undocumented nightly job looks exactly like an abandoned object until you cut it off.
Is a certificate better than a secret?
Yes, when the workload can keep a private key safe: you eliminate the string that ends up in a configuration file or a chat. Certificates live in the keyCredentials collection, separate from the passwordCredentials that hold secrets. A managed identity remains preferable when it is possible.
Does App Instance Lock protect my existing applications?
No: its activation by default since June 2026 applies only to new applications. And even when enabled, the lock does not erase local credentials already added to a service principal, which keep working. Cleaning up what already exists remains your responsibility.
Where to start
Four-step action plan
- Run the read-only inventory (step 2) and compare
apps.csvandserviceprincipals.csvfrom one sweep to the next. - Handle
NeverExpirescredentials first, then those in theExpiringbucket at 7 and 30 days. - Check the app management policy before automating rotation, to avoid a 400 error.
- Disable, do not delete, dormant and ownerless identities; delete after a full cycle without complaints.
If your organization has Workload ID Premium, plug in the staleAppCreds recommendation now, keeping in mind that it is in preview. Otherwise, rely on the dormancy computed from sign-in logs and record unused-credential detection as unavailable. Two items remain manual: template-based applications, to be reported to the vendor, and an owner who refuses a renewal, which requires arbitration by the workload manager.
Further reading
- Microsoft Entra recommendation: remove unused credentials (preview): definition of "unused", roles, permissions, Graph calls and license.
- Configure restrictions on application configuration: enforce a maximum lifetime on secrets and certificates, or block secrets.
- App instance property lock gets a scoping mechanism (Michev): limits of the lock and cleanup of credentials already added.
- Microsoft Entra Workload ID: lifecycle management and monitoring (Thomas Naunheim): recommendations, activity reports and access reviews for workload identities.
- Security best practices for application properties in Microsoft Entra ID: choosing between managed identity, certificate and secret.



