Public/Configuration/New-AdminUser.ps1
function New-AdminUser() { param( [Parameter(Mandatory)] [string]$TenantId ) Connect-CustomerGraph -CustomerTenantId $TenantId -FlowType "Delegated" -Force $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-ModuleLog -Message "Created Jysk IT Administrator: $($AdminUser.UserPrincipalName) with password $($PasswordProfile.Password)" -Level Info -Component 'AdminUser' } else { Write-ModuleLog -Message "Jysk IT Administrator already exists" -Level Info -Component 'AdminUser' $AdminUser = $Users | Where-Object { $_.UserPrincipalName -eq "jyskit-adm@$($CustomerInitialDomain.Name)" } } } catch { Write-ModuleLog -Message "Failed to create Jysk IT Administrator: $_" -Level Error -Component 'AdminUser' } # 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-ModuleLog -Message "Assigned Jysk IT Administrator to Global Administrator group" -Level Info -Component 'AdminUser' } else { Write-ModuleLog -Message "Jysk IT Administrator is already a member of Global Administrator group" -Level Info -Component 'AdminUser' } } catch { Write-ModuleLog -Message "Failed to assign Jysk IT Administrator to Global Administrator group: $_" -Level Error -Component 'AdminUser' } } |