Public/TenantConfiguration/New-AdminUser.ps1

function New-AdminUser() {
    param(
        [Parameter(Mandatory)]
        [string]$TenantId
        )

    Connect-CustomerGraph -CustomerTenantId $TenantId

    $CustomerOrganization = Get-MgOrganization

    $CustomerInitialDomain = $CustomerOrganization.VerifiedDomains | Where-Object { $_.IsInitial -eq $true }

    # Create Jysk IT Administrator
    try {
        $Users = Get-MgUser -All
        if ($Users.UserPrincipalName -notcontains "jyskit-adm@$($CustomerInitialDomain.Name)") {
            Write-Host "Jysk IT Administrator does not exist, creating.."
            $PasswordProfile = @{
                Password                             = (Get-RandomPassword -PasswordLength 16)
                ForceChangePasswordNextSignIn        = $false
                ForceChangePasswordNextSignInWithMfa = $false
            }
            $AdminUser = New-MgUser -DisplayName "Jysk IT Administrator" -PasswordProfile $PasswordProfile  -AccountEnabled -MailNickname "jyskit-adm" -UserPrincipalName "jyskit-adm@$($CustomerInitialDomain.Name)" -ErrorAction Stop
            Write-Host "Created Jysk IT Administrator: $($AdminUser.UserPrincipalName) with password $($PasswordProfile.Password)" -ForegroundColor Green
        }
        else {
            Write-Host "Jysk IT Administrator already exists, skipping.." -ForegroundColor Yellow
            $AdminUser = $Users | Where-Object { $_.UserPrincipalName -eq "jyskit-adm@$($CustomerInitialDomain.Name)" }
        }
    
    }
    catch {
        throw "Failed to create Jysk IT Administrator: $_"
    }
    
    # Assign to Global Administrator group
    try {
        $Role = Get-MgDirectoryRole | Where-Object { $_.DisplayName -eq "Global Administrator" }
        $GlobalAdmins = Get-MgDirectoryRoleMemberAsUser -DirectoryRoleId $Role.Id -ErrorAction Stop
        if ($GlobalAdmins.Id -notcontains $AdminUser.Id) {
            New-MgDirectoryRoleMemberByRef -DirectoryRoleId $Role.Id -BodyParameter @{"@odata.id" = "https://graph.microsoft.com/v1.0/directoryObjects/$($AdminUser.Id)" } -ErrorAction Stop
            Write-Host "Assigned Jysk IT Administrator to Global Administrator group" -ForegroundColor Green
        }
        else {
            Write-Host "Jysk IT Administrator is already a member of Global Administrator group" -ForegroundColor Yellow
        }
    }
    catch {
        throw "Failed to assign Jysk IT Administrator to Global Administrator group: $_"
    }
}