Fix: New-AzADServicePrincipal Error - Resource does not exist
The Context
We use several Azure DevOps pipelines to automate the creation of Service Principals using:
New-AzADServicePrincipal -DisplayName $AzServicePrincipalName -ErrorAction "Stop"
Recently, these started failing intermittently, requiring manual intervention to clean up or complete the registration.
The Error
Could not create the ServicePrincipal: Resource '<objectid>' does not exist or one of its queried reference-property objects are not present.
The Fix
This failure is a direct result of Entra ID’s eventual consistency (replication lag). When New-AzADServicePrincipal is called without an existing application, it tries to create both the App Registration and the Service Principal (Enterprise Application) in one go. If the Service Principal creation attempts to reference an Application ID that hasn’t fully replicated across the Entra ID global infrastructure, the command fails.
The solution is to decouple the process: create the Application Registration explicitly, wait for replication, and then create the Service Principal.
try {
# 1. Check if SP already exists
$sp = Get-AzADServicePrincipal -DisplayName $spName -ErrorAction SilentlyContinue
if (-not $sp) {
# 2. Check if app already exists
$app = Get-AzADApplication -DisplayName $spName -ErrorAction SilentlyContinue
if (-not $app) {
# 3. Create the app registration explicitly
$app = New-AzADApplication -DisplayName $spName -ErrorAction Stop
Write-Host "Created application $spName" -ForegroundColor Yellow
# 4. Wait for Entra ID replication
Start-Sleep -Seconds 15
}
else {
Write-Host "Application with that name already exists." -ForegroundColor Green
}
# 5. Create the SP from the app's AppId
$sp = New-AzADServicePrincipal -ApplicationId $app.AppId -ErrorAction Stop
Write-Host "Created service principal $spName" -ForegroundColor Yellow
}
else {
Write-Host "A service principal with that name already exists." -ForegroundColor Green
}
}
catch {
throw "Could not create the ServicePrincipal: $($_.Exception.Message)"
}