It`s done!
#connecting to Graph using the corresponding permissions
Connect-MgGraph -Scopes User.ReadWrite.All, Organization.Read.All
#importing the excel file containing the user and group information
$NewUsers = Import-Excel -Path "B:\PowerShell\users.xlsx"
#creating password; it will be the same for all users
$PasswordProfile = @{
Password = "Helo123!"
ForceChangePasswordNextSignIn = $true
ForceChangePasswordNextSignInWithMfa = $true
}
#creating all users;
foreach ($user in $NewUsers) {
New-MgUser -UsageLocation $user.UsageLocation `
-GivenName $user.GivenName `
-Surname $user.SurName `
-DisplayName $user.DisplayName `
-MailNickName $user.MailNickName `
-UserPrincipalName $user.UserPrincipalName `
-PasswordProfile $PasswordProfile `
-Department $user.Department `
-AccountEnabled
}
Write-Host " "
Write-Host "Accounts Creation Completed. License assignment in progress...." -ForegroundColor Green
Write-Host " "
#getting the license
$License = Get-MgSubscribedSku -All | Where SkuPartNumber -eq 'ENTERPRISEPREMIUM'
#assigning the license
foreach ($user in $NewUsers) {
Set-MgUserLicense -UserId $user.UserPrincipalName `
-AddLicenses @{SkuId = $License.SkuId} `
-RemoveLicenses @()
}
Write-Host " "
Write-Host "All accounts have been assigned with liceses." -ForegroundColor Green
#importing the required information(the tab called "groups")
$NewGroups = Import-Excel -Path "B:\PowerShell\users.xlsx" -WorksheetName "Groups"
Write-host "Group creation based on the excel file in progress..." -ForegroundColor Green
#creating groups based on the provided information + assigning group owner
foreach ($group in $NewGroups){
New-MgGroup -DisplayName $group.DisplayName `
-MailEnabled:$False `
-MailNickName $group.MailNickName `
-SecurityEnabled `
-GroupTypes Unified
$Owner = (Get-MgUser | Where-Object {$_.DisplayName -eq $group.Owner}).ID
$Groupid = (Get-MgGroup | Where-Object {$_.DisplayName -eq $group.DisplayName }).Id
$params = @{ "@odata.id" = "https://graph.microsoft.com/v1.0/users/$Owner"}
New-MgGroupOwnerByRef -GroupId $GroupId -BodyParameter $params
}
#adding users to the previously created groups
foreach ($user in $NewUsers) {
$DepartmentName = $user.Department
$Groupid = (Get-MgGroup | Where-Object {$_.DisplayName -eq $DepartmentName}).Id
$upn = $user.UserPrincipalName
$params = @{
"@odata.id" = "https://graph.microsoft.com/v1.0/users/$upn"
}
New-MgGroupMemberByRef -GroupId $GroupId -BodyParameter $params
Write-Host "A user has been added to '$($DepartmentName)'" -ForegroundColor Green
}