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)" 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 { Write-Error "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 if ($GlobalAdmins.Id -notcontains $AdminUser.Id) { New-MgDirectoryRoleMemberByRef -DirectoryRoleId $Role.Id -BodyParameter @{"@odata.id" = "https://graph.microsoft.com/v1.0/directoryObjects/$($AdminUser.Id)" } 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 { Write-Error "Failed to assign Jysk IT Administrator to Global Administrator group: $_" } # Check if password has been set, if this is a new user. $PasswordProfile = Get-Variable -Name PasswordProfile -Scope Global -ErrorAction SilentlyContinue if($AdminUser) { if($PasswordProfile) { $AdminUser | Add-Member -MemberType NoteProperty -Name "Password" -Value $PasswordProfile.Password } $AdminUser } } |