Update-MgUser – Office 365 for IT Pros https://office365itpros.com Mastering Office 365 and Microsoft 365 Wed, 24 Apr 2024 14:09:51 +0000 en-US hourly 1 https://i0.wp.com/office365itpros.com/wp-content/uploads/2024/06/cropped-Office-365-for-IT-Pros-2025-Edition-500-px.jpg?fit=32%2C32&ssl=1 Update-MgUser – Office 365 for IT Pros https://office365itpros.com 32 32 150103932 Creating New Azure AD User Accounts and Updating Passwords with the Microsoft Graph PowerShell SDK https://office365itpros.com/2022/11/28/azure-ad-account-creation/?utm_source=rss&utm_medium=rss&utm_campaign=azure-ad-account-creation https://office365itpros.com/2022/11/28/azure-ad-account-creation/#comments Mon, 28 Nov 2022 01:00:00 +0000 https://office365itpros.com/?p=58066

Manage User Accounts with the New-MgUser and Update-MgUser Cmdlets

In March 2022, I wrote about the basics of Azure AD account management using the Microsoft Graph PowerShell SDK. One of the things that I left out of that article was Azure AD account creation. I omitted this detail because it was already covered in another article, where I compare creating an account using cmdlets from the old Azure AD module and the SDK. I’ll cover the basic points here

Connecting to the Microsoft Graph SDK

Before we can create or update accounts, we must connect to the SDK endpoint with the required permissions:

Connect-MgGraph -Scopes User.ReadWrite.All, Directory.ReadWrite.All
Select-MgProfile Beta

Password Profiles

The New-MgUser cmdlet creates a new account. To run New-MgUser, we need a password profile. A password profile is a Microsoft Graph resource that contains a password and associated settings. It can be as simple as a password with no settings, but a password profile can also include settings like ForceChangePasswordNextSignIn to force a user account to change their password after they next sign into Azure AD.

New-MgUser uses a hash table for the password profile. The example code shown below populates the hash table with a new password (generated using the GeneratePassword .NET method as a random 10-character string containing special characters, numbers, and upper- and lower-case letters). The ForceChangePasswordNextSignIn setting is True to force the new user to set a new password after they sign in.

Add-Type -AssemblyName 'System.Web'
$NewPassword = [System.Web.Security.Membership]::GeneratePassword(10, 3)
$NewPasswordProfile = @{}
$NewPasswordProfile["Password"]= $NewPassword
$NewPasswordProfile["ForceChangePasswordNextSignIn"] = $True

The hash table now contains values like this:

Name                           Value
----                           -----
Password                       4i_gb6OK?{
ForceChangePasswordNextSignIn  True

Creating a New Azure AD User Account with New-MgUser

To create the new account, run the New-MgUser cmdlet. It’s obviously important to include as many details as possible about the new user account, especially the settings exposed by Microsoft 365 in places like the user profile card or the Organization Explorer feature in Outlook and Teams.

# Azure AD Account Creation - the hard coded way
$DisplayName = "Jeff Atkinson"
$NewUser = New-MgUser -UserPrincipalName "Jeff.Atkinson@Office365ITPros.com" `
  -DisplayName "Jeff Atkinson (Information Technology)" `
  -PasswordProfile $NewPasswordProfile -AccountEnabled `
  -MailNickName Jeff.Atkinson -City NYC `
  -CompanyName "Office 365 for IT Pros" -Country "United States" `
  -Department "IT Operations" -JobTitle "GM Operations" `
  -BusinessPhones "+1 676 830 1101" -MobilePhone "+1 617 4466615" `
  -State "New York" -StreetAddress "1, Avenue of the Americas" `
  -Surname "Atkinson" -GivenName "Jeff" `
  -UsageLocation "US" -OfficeLocation "NYC"
If ($NewUser) { Write-Host ("Successfully added the {0} account" -f $NewUser.DisplayName) 
  } Else { Write-Host ("Failure adding the {0} account - exiting" -f $DisplayName); break }

The usage location is a two-character ISO-3166 country code to show where the account consumes services, and it’s important to set the value correctly so that the license assignment works properly. After creating a new account, you’ll need to assign it some licenses to allow access to Microsoft 365 services. See this article for more information.

The code to add a new account shown above is a one-off command. However, it’s the principal that counts and it is straightforward to take the code and amend it so that it uses parameters or input such as a CSV file (like that shown in Figure 1) holding details of new users. In the latter case, after loading the records into an array, you could then loop through the records to add each account. Here’s an example of doing just that:

CSV file to drive Azure AD account creation
Figure 1: CSV file to drive Azure AD account creation

# Azure AD account creation - driven by data imported from a CSV file
$Accounts = Import-CSV c:\temp\Accounts.CSV
ForEach ($Account in $Accounts) {
  $NewPassword = [System.Web.Security.Membership]::GeneratePassword(10, 3)
  $NewPasswordProfile = @{}
  $NewPasswordProfile["Password"]= $NewPassword
  $NewPasswordProfile["ForceChangePasswordNextSignIn"] = $True
  $MailNickname = $Account.First + "." + $Account.Surname
  $DisplayName = $Account.First + " " + $Account.Surname
  Write-Host ("Processing the {0} account" -f $DisplayName)
  $NewUser = New-MgUser -UserPrincipalName $Account.UserPrincipalName `
  -DisplayName $DisplayName `
  -PasswordProfile $NewPasswordProfile `
  -MailNickName $MailNickName -City $Account.City `
  -CompanyName $Account.Company -Country $Account.Country `
  -Department $Account.Department -JobTitle $Account.Title `
  -BusinessPhones $Account.Phone -MobilePhone $Account.Mobile `
  -State $Account.State -StreetAddress $Account.Street `
  -Surname $Account.Surname -GivenName $Account.First `
  -UsageLocation $Account.Location -OfficeLocation $Account.Office `
  -AccountEnabled
 If ($NewUser) { Write-Host ("Successfully added the {0} account" -f $NewUser.DisplayName) 
  } Else { Write-Host ("Failure adding the {0} account - exiting" -f $DisplayName); break }
}

Finishing up Azure AD Account Creation

To complete the account creation process, you might want to send email to the administrator accounts with details of the new account (Figure 2). This task is easily accomplished with a Graph method to create and send email (explained in this article).

Email notification about the creation of a new Azure AD user account

Azure AD account creation
Figure 2: Email notification about the creation of a new Azure AD user account

To help illustrate the flow of creating a new account complete with license assignment and email notification, I’ve uploaded a script to GitHub. The code is not a functional script because it contains once-off commands. Instead, it’s for you to play with and create your own version.

Updating a User Account with a New Password

To change an Azure AD account password, create a password profile as above and then run the Update-MgUser cmdlet. If you don’t want to force the user to create a new password after they sign in, make sure that the ForceChangePasswordNextSignIn setting in the password profile is false, and then run:

Update-MgUser -UserId Terry.Hegarty@Office365itpros.com -PasswordProfile $NewPassword

Updating a user’s password generates a continual access evaluation (CAE) event for CAE. This means that “enlightened” applications like the Office web apps learn about the existence of the new password and will force the user to reauthenticate with the new password to continue working.

Azure AD Account Creation Not Hard with the SDK

Creating a new Azure AD user account with the Microsoft Graph PowerShell SDK isn’t difficult. The hardest thing might be to come up with a good temporary password to assign to the account. Good luck if you’re moving scripts from the old Azure AD or MSOL modules before Microsoft deprecates these modules in 2023. It just takes a little time and maybe a lot of persistence.


Insight like this doesn’t come easily. You’ve got to know the technology and understand how to look behind the scenes. Benefit from the knowledge and experience of the Office 365 for IT Pros team by subscribing to the best eBook covering Office 365 and the wider Microsoft 365 ecosystem.

]]>
https://office365itpros.com/2022/11/28/azure-ad-account-creation/feed/ 1 58066
Updating Microsoft 365 User Accounts to use a New Domain https://office365itpros.com/2022/10/18/update-user-email-upns/?utm_source=rss&utm_medium=rss&utm_campaign=update-user-email-upns https://office365itpros.com/2022/10/18/update-user-email-upns/#comments Tue, 18 Oct 2022 01:00:00 +0000 https://office365itpros.com/?p=57481

Update User Email Addresses and User Principal Names

A recent reader question asked about the best way to update a bunch of user accounts after the organization buys a new vanity domain and wants the domain used for email addresses and user principal names (sign-in addresses). This sometimes happens when a business goes through a rebranding exercise and ends up with a new name. The requirement to update email addresses and user principal names also occurs in tenant-to-tenant migrations.

Tenant-to-tenant migrations are a specialized kind of activity that’s usually managed with software built for this purpose. We won’t plunge into the challenges that these projects can encounter. Instead, we’ll focus on the scenario where someone in authority decides that all accounts should use different email addresses and user principal names.

Registered Domains

The first requirement is to add the domain to Office 365. Until this is done, you cannot use the domain. Once the domain is known to the tenant, it appears in the set of verified domains seen in the Microsoft 365 admin center (Figure 1).

Verified domains in a Microsoft 365 tenant.
Figure 1: Verified domains in a Microsoft 365 tenant

After verifying the domain for Microsoft 365, we can write some code to ask the administrator what domain to use. Here’s an example that uses the Get-MgOrganization cmdlet from the Microsoft Graph PowerShell SDK to fetch the verified domains:

Connect-MgGraph -Scopes Directory.Read.All, User.ReadWrite.All
# Get tenant information and the verified domains for the tenant
$TenantInfo = (Get-MgOrganization)
[array]$Domains = $TenantInfo.VerifiedDomains.Name
$DomainsList = $Domains -join ", "
Write-Host "Verified domains for this tenant:"
Write-Host "---------------------------------"
Write-Host ""
$Domains
Write-Host ""
$DomainToUse = Read-Host "What domain do you want to use for primary SMTP addresses and UPNs"
Write-Host ""
If ($DomainToUse -notin $Domains) {Write-Host ("The selected domain ({0}) is not in the set supported by the tenant ({1}). Please try again." -f $DomainToUse, $DomainsList); break }
$CompareDomain = "*" + $DomainToUse + "*"

Finding Mail Recipients

The next step is to find mail-enabled recipients that have email addresses that might need updating. This code finds user mailboxes, shared mailboxes, group mailboxes (for Microsoft 365 groups), distribution lists, and security-enabled distribution lists.

For each object, the code calculates a new primary SMTP address based on their existing address by swapping the existing domain for the new domain. A check makes sure that the new address isn’t already in use, and if it is, creates a new address by adding “.EXO” to the username. The code then checks if it’s necessary to update the user principal name for the Entra ID accounts used by user mailboxes and shared mailboxes. An account might already use the new domain, so the code checks the account’s current user principal name and updates it with the new domain if necessary.

The output is captured in a PowerShell list that’s exported to a CSV file.

If (!($DomainToUse)) {
   Write-Host "No domain to move to is defined. Please make sure that the $DomainToUse variable is defined"
   Break
} Else {
   Write-Host ("Processing accounts to move them to the {0} domain..." -f $DomainToUse)
}

[array]$Recipients = Get-Recipient -ResultSize Unlimited -RecipientTypeDetails UserMailbox, SharedMailbox, GroupMailbox, MailUniversalDistributionGroup, MailUniversalSecurityGroup, DynamicDistributionGroup

$i = 0
$Report = [System.Collections.Generic.List[Object]]::new()
ForEach ($R in $Recipients) {
     $i++
     If ($R.PrimarySmtpAddress.Split("@")[1] -ne $DomainToUse) { #Need to process this mailbox
      Write-Host ("Processing {0} {1} ({2}/{3})" -f $R.RecipientTypeDetails, $R.DisplayName, $i, $Recipients.Count)
      $NewUPN = $Null
      # Figure out new email address
      $NewAddress = $R.Alias + "@" + $DomainToUse
      # Check that the address is available
      $Status = Get-Recipient -Identity $NewAddress -ErrorAction SilentlyContinue
      # If we get a status the recipient address already exists, so create a new address
      If ($Status) { $NewAddress = $M.Alias + ".EXO@" + $DomainToUse }
      
      # Figure out if the account's user principal name needs to change
      If ($R.RecipientType -eq "SharedMailbox" -or $R.RecipientType -eq "UserMailbox") {
        $UPNDomain = $R.WindowsLiveId.Split("@")[1]
        If ($UPNDomain -ne $DomainToUse) { # New UPN needed
          $NewUPN = $R.WindowsLiveId.Split("@")[0] + "@" + $DomainToUse
          $Status = Get-MgUser -UserId $NewUPN -ErrorAction SilentlyContinue
          If ($Status) { # UPN already exists, so create a new one
            $NewUPN = $R.WindowsLiveId.Split("@")[0] + ".EXO@" + $DomainToUse }
          }
       }

      $ReportLine   = [PSCustomObject] @{ 
         DisplayName            = $R.DisplayName
         OldUPN                 = $R.WindowsLiveId
         NewUPN                 = $NewUPN
         PrimarySmtpAddress     = $R.PrimarySmtpAddress
         NewAddress             = $NewAddress
         Type                   = $R.RecipientTypeDetails
         Alias                  = $R.Alias
    }
    $Report.Add($ReportLine) }
}
$Report = $Report | Sort-Object Type
$Report | Export-CSV -NoTypeInformation c:\temp\MailObjects.Csv

Administrators can check the CSV to remove any mail-enabled recipients they don’t want to receive new email addresses (Figure 2).

Update User Email Addresses with a New Domain

The next step is reads in and processes an array of objects from the updated CSV file.

The code uses a Switch statement to check the object type and calls the appropriate cmdlet to assign the new primary SMTP address to the object. If the account used for a mailbox (user or shared) requires an update for its user principal name, we go ahead and do it.

The final step in the loop through the objects is to report what’s been done, noting the old and new SMTP address and the old and new user principal name.

# Process mail objects array to update primary SMTP addresses and UPNs as necessary
[array]$MailObjects = Import-CSV MailObjects.CSV
$Report = [System.Collections.Generic.List[Object]]::new()

Write-Host "Processing mail-enabled objects..."
$i = 0
ForEach ($M in $MailObjects)  {
   $i++
   Write-Host ("Processing {0} {1} ({2}/{3})" -f $M.Type, $M.DisplayName, $i, $MailObjects.Count)

   # Assign new primary SMTP Address
   Switch ($M.Type) {
      "DynamicDistributionGroup" { # Dynamic distribution list
        Set-DynamicDistributionGroup -Identity $M.PrimarySmtpAddress -PrimarySmtpAddress $NewAddress
     }
      "GroupMailbox" { # Microsoft 365 group
        Set-UnifiedGroup -Identity $M.PrimarySmtpAddress -PrimarySmtpAddress $NewAddress
     }
      "MailUniversalDistributionGroup" { # Distribution list
        Set-DistributionGroup -Identity $M.PrimarySmtpAddress -PrimarySmtpAddress $NewAddress
     }
      "MailUniversalSecurityGroup" { #Mail-enabled security group
        Set-DistributionGroup -Identity $M.PrimarySmtpAddress -PrimarySmtpAddress $NewAddress
     }
      "SharedMailbox" { # Shared mailbox
        Set-Mailbox -Identity $M.PrimarySmtpAddress -WindowsEmailAddress $NewAddress 
     }
      "UserMailbox" { # User mailbox
        Set-Mailbox -Identity $M.PrimarySmtpAddress -WindowsEmailAddress $NewAddress 
     }
    }

   # Update UPN if necessary
   If ($M.NewUPN) {  
     Update-MgUser -UserId $M.UPN -UserPrincipalName $M.NewUPN }

   $ReportLine   = [PSCustomObject] @{ 
          DisplayName            = $M.DisplayName
          OldUPN                 = $M.UPN
          NewUPN                 = $M.NewUPN
          OldPrimarySmtpAddress  = $M.PrimarySmtpAddress
          NewPrimarySmtpAddress  = $M.NewAddress
          Type                   = $M.Type
          Alias                  = $M.Alias
    }
    $Report.Add($ReportLine) 

} # End ForEach 
Write-Host "All done!"

Figure 3 shows an example of the report that allows administrators to check that the expected email addresses and user principal names are in place.

The updated accounts with new primary SMTP addresses and some new user principal names
Figure 3: The updated accounts with new primary SMTP addresses and some new user principal names

The User Issue

Updated user principal names take effect the next time users sign in. If you want to force the switchover, you could disconnect users from their current sessions by invalidating refresh tokens using the Graph revokeSignInSessions API. Invaliding access tokens forces users to reauthenticate and reconnect, and to do that, they must use their new user principal names.

Be aware that some issues exist when changing user principal names such as the need to set up the new user principal name on the Microsoft Authenticator app so that MFA challenges work It’s worthwhile reading through this Microsoft article to understand and test problems that users might encounter in your organization. Knowing what might happen and being prepared to fix the issues will ensure a smoother transition.

Any change to the way people sign-in is likely to cause some angst if it’s not communicated clearly so that everyone understands why the change is happening and what they must do to sign-in to access services.

Tidying Up Entra ID

The process outlined above takes care of the bulk of the work. If some Entra ID accounts that don’t have email addresses need to receive updated user principal names, you can do this with the Update-MgUser cmdlet from the Microsoft Graph PowerShell SDK.

Giving accounts new email addresses and user principal names isn’t a difficult technical challenge. The likely problems arise in preparation and communication. Isn’t that always the way?


Keep up with the changing world of the Microsoft 365 ecosystem by subscribing to the Office 365 for IT Pros eBook. Monthly updates mean that our subscribers learn about new developments as they happen.

]]>
https://office365itpros.com/2022/10/18/update-user-email-upns/feed/ 15 57481
Basic User Account Management with the Microsoft Graph PowerShell SDK https://office365itpros.com/2022/03/24/entra-id-user-accounts-powershell/?utm_source=rss&utm_medium=rss&utm_campaign=entra-id-user-accounts-powershell https://office365itpros.com/2022/03/24/entra-id-user-accounts-powershell/#comments Thu, 24 Mar 2022 01:00:00 +0000 https://office365itpros.com/?p=54188

Preparing to Migrate Away from Old AzureAD cmdlets

Updated: 15 March, 2023

Manage Entra ID user accounts

I received a lot of reaction when I described Microsoft’s new deprecation schedule for the AzureAD and MSOL modules. In summary, you have until 30 March 2024 to update scripts which assign licenses to user accounts. After this, Microsoft will disable the cmdlets. The other cmdlets will continue working after Microsoft deprecates the modules. However, they’ll be out of support, which is not a good foundation for PowerShell scripts used to automate administrative processes, like managing Entra ID user accounts.

With time running out, it’s obvious that tenants need to inventory and upgrade scripts. One reaction I received was that there’s a dearth of information to help people who are less familiar with PowerShell and might have inherited ownership of some scripts. My response is that the community will publish examples over time, just like they did when Microsoft launched the AzureAD module in 2016 and the Exchange Online management REST-based cmdlets at Ignite 2019. Let’s hope this is true.

Over on Practical365.com, I compare creating a new Entra ID user account and assigning licenses to the account using both the old AzureAD module and the Microsoft Graph PowerShell SDK. In this post, I consider some additional basic user account management actions.

Connections

The basics of using the Microsoft Graph PowerShell SDK (the SDK) is to connect. You can connect interactively (delegated access) or with certificate-based authentication (application access). You can also run SDK cmdlets in Azure Automation runbooks. The simplest approach is to run Connect-MgGraph interactively, which signs into the Graph using the account you signed into PowerShell with.

Scopes

SDK cmdlets interact with Microsoft Graph APIs. A big difference between the SDK and AzureAD modules is that the SDK forces you to request the set of Graph permissions you want to use. The SDK uses a service principal to hold the permissions, and over time, that service principal might become overly permissioned. It’s a thing to keep an eye on.

In this example, we define an array of Graph permissions we wish to use, and then connect. If you request a permission that the SDK service principal doesn’t already hold, you’ll see an administrator prompt for consent.

$RequiredScopes = @("Directory.AccessAsUser.All", "Directory.ReadWrite.All", "User.ReadWrite.All", “User.Read.All”)
Connect-MgGraph -Scopes $RequiredScopes -NoWelcome

Welcome To Microsoft Graph!

Updating Properties for Entra ID User Accounts

Let’s assume that you’ve created the Sue.Ricketts@Office365itpros.com account using the New-MgUser cmdlet as described in this article and stored the user identifier for the account in the $UserId variable.

$UserId = (Get-MgUser -UserId Sue.Ricketts@office365itpros.com).Id

To update the properties of a user account, run the Update-MgUser cmdlet.

Update-MgUser -UserId $UserId -JobTitle "Senior Editor" -State NY

Updating Email Properties for an Account

You can’t update the proxyAddresses property of a user account because the Graph treats it as read-only, possibly because Exchange Online takes care of email proxy address management. However, if you change the UserPrincipalName property of an account, Update-MgUser sets the primary SMTP address of the account to match the new user principal name. The logic here is likely that it is best practice to match the user principal name and primary SMTP address. In most cases, this is true and it’s a good idea to have the cmdlet behave like it does. However, in some circumstances, you might decide to have different values in these properties.

In both situations, you should use the Exchange Online Set-Mailbox cmdlet to update proxy addresses. For example, this command adds a new SMTP proxy address to the mailbox identified by the $UserId variable:

Set-Mailbox -Identity $UserId -EmailAddresses @{Add="Johnnie.West@Office365itpros.com"}

This command updates the primary SMTP address for the mailbox without changing the user principal name:

Set-Mailbox -Identity $UserId -WindowsEmailAddress Johnnie.West@Office365itpros.com

Exchange Online uses a dual-write mechanism to make sure that any change made to mailboxes happens simultaneously to the underlying user account.

Updating a User’s Manager

The manager of a user account is updated by reference (to their account) rather than simply updating a property. To update the manager of a user account, run the Set-MgUserManagerByRef cmdlet after storing the identifier of the manager’s account in a variable:

$ManagerId = (Get-MgUser -UserId Terry.Hegarty@office365itpros.com).Id
Set-MgUserManagerByRef -UserId $UserId `
   -AdditionalProperties @{
     "@odata.id" = "https://graph.microsoft.com/v1.0/users/$ManagerId" }

To check that the manager update was successful, we need to fetch the manager’s details (expanded into a dictionary object) and retrieve the property we want.

$ManagerData = Get-Mguser -UserId $UserId -ExpandProperty Manager
$ManagerData.Manager.AdditionalProperties['displayName']
Terry Hegarty

You can also use the Get-MgUserManager cmdlet to return the manager of an account.

Get-MgUserManager -UserId Chris.Bishop@Office365itpros.com | Select-Object @{n="DisplayName";e={$_.AdditionalProperties.displayName}},@{n="UserPrincipalName";e={$_.AdditionalProperties.userPrincipalName}}

DisplayName UserPrincipalName
----------- -----------------
James Ryan  James.Ryan@office365itpros.com

Obviously, Microsoft has made defining and retrieving the manager of an account more complex than it needs to be. It would be nice if they would hide the complexity in code and deliver some straightforward cmdlets that don’t create friction when the time comes to update scripts.

Another way of updating user account properties is with the Invoke-MgGraphRequest cmdlet, which runs a Graph API query. The advantage of this cmdlet is that if you can’t find a way to do something with an SDK cmdlet, you can refer to the Microsoft Graph documentation, find some example code, and run or repurpose it.

In this example, we create a hash table to hold the properties we want to update, convert the table to a JSON object, and pass it to a PATCH query run by Invoke-MgGraphRequest:

$Parameters = @{
   JobTitle = "Managing Editor, Periodicals"
   State = "Vermont"
   OfficeLocation = "Burlington" } | ConvertTo-Json
Invoke-MgGraphRequest -Method PATCH -Uri "https://graph.microsoft.com/v1.0/users/Sue.Ricketts@office365itpros.com" -Body $Parameters -ContentType "application/json; charset=utf-8"

Delete a User Account

The Remove-MgUser cmdlet soft-deletes a user account and moves it into Entra ID’s deleted items container, where it remains for 30 days until Entra ID permanently deletes the object. The cmdlet is very simple, and it doesn’t prompt for confirmation before proceeding to delete a user account.

Remove-MgUser -UserId $UserId

If you need to restore a soft-deleted account, run the Restore-MgUser cmdlet and pass the object identifier of the account you want to restore. See this article for information about how to list the set of soft-deleted user accounts.

Restore-MgUser -UserId $UserId

I’ve experienced some issues with the Restore-MgUser cmdlet in the 1.9.3 release of the SDK which I have reported to Microsoft. Basically, the cmdlet doesn’t work in this release. I’m sure the bug will be fixed soon.

Finding User Accounts

We’ve already seen how the Get-MgUser cmdlet fetches information for an individual user account. It also fetches sets of accounts. To fetch all the accounts in the tenant, run:

[array]$Users = Get-MgUser -All

I always specify that the variable used as the target for a set of objects is an array. This makes it easy to find how many objects are returned, as in:

Write-Host $Users.Count “User accounts found”

Note that unlike Graph API queries, the Get-MgUser cmdlet takes care of data pagination for the query and fetches all available objects.

If you don’t specify the All switch, the cmdlet fetches the first 100 accounts. You can fetch a specific number of accounts using the Top parameter, up to a maximum of 999.

[array]$Top500 = Get-MgUser -Top 500

The Filter parameter uses server-side filtering to restrict the amount of data returned. For instance, here’s how to find all the guest accounts in a tenant:

[array]$Guests = Get- MgUser -Filter "usertype eq 'Guest'" -All

While this filter returns the accounts who usage location (for Microsoft 365 services) is the U.S.

Get-MgUser -Filter "usagelocation eq 'US'"

You can combine properties in a filter. For example:

Get-MgUser -Filter "usagelocation eq 'US' and state eq 'NY'"

Another interesting filter is to find accounts created in a specific date range. This command finds all tenant non-guest accounts created between January 1, 2022 and Matrch 24. Note the trailing Z on the dates. The Graph won’t treat the date as valid if the Z is not present.

Get-MgUser -Filter "createdDateTime ge 2022-01-01T00:00:00Z and createdDateTime le 2022-03-24T00:00:00Z and usertype eq ‘Member’"

Support for SDK Problems via GitHub

Hopefully, the examples listed above are useful in terms of understanding the SDK cmdlets to perform basic management of Entra ID user accounts. If you run into a problem when converting scripts to use SDK cmdlets, you can report the problem (or browse the current known issues) on GitHub. Happy migration!

]]>
https://office365itpros.com/2022/03/24/entra-id-user-accounts-powershell/feed/ 9 54188