4 Start Graph as‐a‐code configuration : delete a tenant - dcasota/m365-scripts GitHub Wiki
Lately, I wanted to delete a tenant programmatically. The website https://learn.microsoft.com/en-us/entra/identity/users/directory-delete-howto contains a few information. This doesn't seem to be entierely possible but here the findings so far.
install-module -name Az
install-module -name Microsoft.Graph
Connect-AzAccount
# Login with the global administrator account of the tenant.
# In my case an external user has the role global administrator for the tenant.
# Use the full tenant account name e.g. name.surname_externaldomain.com#EXT#@internaldomain.onmicrosoft.com
get-azcontext
# Output
Tenant: Tenantname (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)
SubscriptionName SubscriptionId Account Environment
---------------- -------------- ------- -----------
name.surname_externaldomain.com#EXT#@internaldomain.onmicrosoft.com AzureCloud
# should get the same result
get-aztenant
Name Id TenantCategory Domains
---- -- -------------- -------
Tenantname xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx Home {Tenantname.onmicrosoft.com}
# connect to MgGraph : I didn't double check which api permissions are effectively necessary wnd which not.
connect-Mggraph -Scopes 'User.Read.All', 'RoleManagement.ReadWrite.Directory', 'LicenseAssignment.ReadWrite.All','ManagedTenants.ReadWrite.All', 'CrossTenantUserProfileSharing.ReadWrite.All' , 'Policy.ReadWrite.CrossTenantAccess', 'ServicePrincipalEndpoint.ReadWrite.All','IdentityProvider.ReadWrite.All','DelegatedAdminRelationship.ReadWrite.All','AdministrativeUnit.ReadWrite.All'
# This shows if the right permissions were set to access the content if ServicePrincipals so far
Get-MgServicePrincipal
# disable any blocking service principals: DOES NOT WORK. NOT ENOUGH PRIVILEGES
$ServicePrincipalUpdate =@{ "accountEnabled" = "false" }
Get-MgServicePrincipal | ForEach-Object { Update-MgServicePrincipal -ServicePrincipalId $_.Id -BodyParameter $ServicePrincipalUpdate }
# remove applications and service principal
Get-MgServicePrincipal | ForEach-Object { Remove-MgServicePrincipal -ServicePrincipalId $_.Id }
# this cmdlet is not available.
# remove-aztenant -tenantid a3d588c8-8e32-4b7a-8d7f-23ad7b5458b6