@@ -207,6 +207,35 @@ function Invoke-MsIdAgentIdInteractive {
207207 $principal1 = New-MsIdAgentIdentityBlueprintPrincipal
208208 Write-Host " Created Service Principal ID: $ ( $principal1.id ) " - ForegroundColor Green
209209
210+ # Wait for service principal to be available (backend replication delay)
211+ Write-Host " Waiting for service principal to be available..." - ForegroundColor Yellow
212+ $maxWaitSeconds = 60
213+ $waitInterval = 5
214+ $elapsedSeconds = 0
215+ $spAvailable = $false
216+
217+ while ($elapsedSeconds -lt $maxWaitSeconds ) {
218+ try {
219+ $sp = Get-MgServicePrincipal - ServicePrincipalId $principal1.id - ErrorAction Stop
220+ if ($sp ) {
221+ $spAvailable = $true
222+ Write-Host " Service principal is now available" - ForegroundColor Green
223+ break
224+ }
225+ }
226+ catch {
227+ # Service principal not yet available, continue waiting
228+ }
229+
230+ Start-Sleep - Seconds $waitInterval
231+ $elapsedSeconds += $waitInterval
232+ Write-Host " Waiting... ($elapsedSeconds seconds elapsed)" - ForegroundColor Gray
233+ }
234+
235+ if (-not $spAvailable ) {
236+ Write-Warning " Service principal may not be fully replicated yet. Continuing anyway..."
237+ }
238+
210239 # Step 7: Grant permission to create agent users (only if user chose to have Agent ID users)
211240 if ($hasAgentIDUsers ) {
212241 Write-Host " Granting agent user creation permissions..." - ForegroundColor Yellow
@@ -309,7 +338,7 @@ function Invoke-MsIdAgentIdInteractive {
309338 Write-Host " Creating Agent Users as requested..." - ForegroundColor Yellow
310339 # Get current tenant's domain for UPN
311340 $tenantDomain = (Get-MgOrganization ).VerifiedDomains | Where-Object { $_.IsDefault -eq $true } | Select-Object - First 1 - ExpandProperty Name
312-
341+
313342 # Determine names for the Agent User
314343 if ($useExampleNames ) {
315344 $agentUserDisplayName = " Agent User Example $agentCounter "
@@ -320,15 +349,15 @@ function Invoke-MsIdAgentIdInteractive {
320349 $agentUserDisplayName = " Agent User $agentCounter "
321350 Write-Host " Using default: $agentUserDisplayName " - ForegroundColor Gray
322351 }
323-
352+
324353 $agentUserUpnPrefix = Read-Host " Enter UPN prefix for this Agent User (will be @$tenantDomain )"
325354 if ([string ]::IsNullOrWhiteSpace($agentUserUpnPrefix )) {
326355 $agentUserUpnPrefix = " AgentUser$agentCounter "
327356 Write-Host " Using default prefix: $agentUserUpnPrefix " - ForegroundColor Gray
328357 }
329358 $agentUserUpn = " $agentUserUpnPrefix @$tenantDomain "
330359 }
331-
360+
332361 $agentUser = New-MsIdAgentIDUserForAgentId - DisplayName $agentUserDisplayName `
333362 - UserPrincipalName $agentUserUpn
334363 Write-Host " Created Agent User ID: $ ( $agentUser.id ) " - ForegroundColor Green
0 commit comments