You are currently viewing Manage Bulk Users through Office365 Azure AD PowerShell
office365 azure ad

Manage Bulk Users through Office365 Azure AD PowerShell

You’ll learn how you can manage bulk users through Office365 Azure AD PowerShell. You’ll be using the new Azure Active Directory PowerShell for Graph module and I recommend using the same.

I hope you’re already aware with the power of PowerShell. When there is a requirement for bulk operation then PowerShell is the right tool that can save your time and complete jobs with minimum effort.

Overview

You’ll learn how to create, view, edit, block and delete Office 365 users through Office365 Azure AD PowerShell.

We’ve already discussed in the previous post, how to install required modules and connect to Microsoft Office365 different service with an all-in-one single script.

It would be very helpful to connect all Office 365 services with saved credentials in an encrypted format, so no need to enter the credentials again and again.

Office365 Azure AD
Connect all Office 365 services with saved credentials

Now let’s discuss how we can manage users….

View Office 365 Users

Firstly, we’ll view the existing O365 user’s details, so that can get an idea of what are the user’s properties are available.

Let’s connect to Office365 Azure AD if you’ve not connected PowerShell session already:

# Connect to Azure AD (Newer Module)
Connect-AzureAD
Office365 Azure AD
Connect to Azure AD

View All Users through Office365 Azure AD

You need to run below command to get the all existing O365 users:

#View Azure AD/O365 All Users
Get-AzureADUser
View All Office 365 Users
View All Office 365 Users

You’re able to get only ObjectID, DisplayName, UserPrincipleName and UserType property info because it’s a default view.

For example, if you want to get all the property details of all users then you can customize the output.

Firstly, you want to check what are the methods & properties available of specific commands:

# The Get-Member cmdlet gets the members, the properties and methods, of objects:
Get-AzureADUser | Get-Member
PS C:\> Get-AzureADUser | Get-Member     

   TypeName: Microsoft.Open.AzureAD.Model.User

Name                                          MemberType Definition
----                                          ---------- ----------
Equals                                        Method     bool Equals(System.Object obj), bool Equals(Microsoft.Open.AzureAD.Model.User other), bool Equals(Microsoft.Open.AzureAD.Model.DirectoryObje...
GetHashCode                                   Method     int GetHashCode()
GetType                                       Method     type GetType()
ShouldSerializeAssignedLicenses               Method     bool ShouldSerializeAssignedLicenses()
ShouldSerializeAssignedPlans                  Method     bool ShouldSerializeAssignedPlans()
ShouldSerializeDeletionTimestamp              Method     bool ShouldSerializeDeletionTimestamp()
ShouldSerializeDirSyncEnabled                 Method     bool ShouldSerializeDirSyncEnabled()
ShouldSerializeLastDirSyncTime                Method     bool ShouldSerializeLastDirSyncTime()
ShouldSerializeLegalAgeGroupClassification    Method     bool ShouldSerializeLegalAgeGroupClassification()
ShouldSerializeMail                           Method     bool ShouldSerializeMail()
ShouldSerializeObjectId                       Method     bool ShouldSerializeObjectId()
ShouldSerializeObjectType                     Method     bool ShouldSerializeObjectType()
ShouldSerializeOnPremisesSecurityIdentifier   Method     bool ShouldSerializeOnPremisesSecurityIdentifier()
ShouldSerializeProvisionedPlans               Method     bool ShouldSerializeProvisionedPlans()
ShouldSerializeProvisioningErrors             Method     bool ShouldSerializeProvisioningErrors()
ShouldSerializeProxyAddresses                 Method     bool ShouldSerializeProxyAddresses()
ShouldSerializeRefreshTokensValidFromDateTime Method     bool ShouldSerializeRefreshTokensValidFromDateTime()
ShouldSerializeSipProxyAddress                Method     bool ShouldSerializeSipProxyAddress()
ToJson                                        Method     string ToJson()
ToString                                      Method     string ToString()
Validate                                      Method     System.Collections.Generic.IEnumerable[System.ComponentModel.DataAnnotations.ValidationResult] Validate(System.ComponentModel.DataAnnotation... 
AccountEnabled                                Property   System.Nullable[bool] AccountEnabled {get;set;}
AgeGroup                                      Property   string AgeGroup {get;set;}
AssignedLicenses                              Property   System.Collections.Generic.List[Microsoft.Open.AzureAD.Model.AssignedLicense] AssignedLicenses {get;}
AssignedPlans                                 Property   System.Collections.Generic.List[Microsoft.Open.AzureAD.Model.AssignedPlan] AssignedPlans {get;}
City                                          Property   string City {get;set;}
CompanyName                                   Property   string CompanyName {get;set;}
ConsentProvidedForMinor                       Property   string ConsentProvidedForMinor {get;set;}
Country                                       Property   string Country {get;set;}
CreationType                                  Property   string CreationType {get;set;}
DeletionTimestamp                             Property   System.Nullable[datetime] DeletionTimestamp {get;}
Department                                    Property   string Department {get;set;}
DirSyncEnabled                                Property   System.Nullable[bool] DirSyncEnabled {get;}
DisplayName                                   Property   string DisplayName {get;set;}
ExtensionProperty                             Property   System.Collections.Generic.Dictionary[string,string] ExtensionProperty {get;set;}
FacsimileTelephoneNumber                      Property   string FacsimileTelephoneNumber {get;set;}
GivenName                                     Property   string GivenName {get;set;}
ImmutableId                                   Property   string ImmutableId {get;set;}
IsCompromised                                 Property   System.Nullable[bool] IsCompromised {get;set;}
JobTitle                                      Property   string JobTitle {get;set;}
LastDirSyncTime                               Property   System.Nullable[datetime] LastDirSyncTime {get;}
LegalAgeGroupClassification                   Property   string LegalAgeGroupClassification {get;}
Mail                                          Property   string Mail {get;}
MailNickName                                  Property   string MailNickName {get;set;}
Mobile                                        Property   string Mobile {get;set;}
ObjectId                                      Property   string ObjectId {get;}
ObjectType                                    Property   string ObjectType {get;}
OnPremisesSecurityIdentifier                  Property   string OnPremisesSecurityIdentifier {get;}
OtherMails                                    Property   System.Collections.Generic.List[string] OtherMails {get;set;}
PasswordPolicies                              Property   string PasswordPolicies {get;set;}
PasswordProfile                               Property   Microsoft.Open.AzureAD.Model.PasswordProfile PasswordProfile {get;set;}
PhysicalDeliveryOfficeName                    Property   string PhysicalDeliveryOfficeName {get;set;}
PostalCode                                    Property   string PostalCode {get;set;}
PreferredLanguage                             Property   string PreferredLanguage {get;set;}
ProvisionedPlans                              Property   System.Collections.Generic.List[Microsoft.Open.AzureAD.Model.ProvisionedPlan] ProvisionedPlans {get;}
ProvisioningErrors                            Property   System.Collections.Generic.List[Microsoft.Open.AzureAD.Model.ProvisioningError] ProvisioningErrors {get;}
ProxyAddresses                                Property   System.Collections.Generic.List[string] ProxyAddresses {get;}
RefreshTokensValidFromDateTime                Property   System.Nullable[datetime] RefreshTokensValidFromDateTime {get;}
ShowInAddressList                             Property   System.Nullable[bool] ShowInAddressList {get;set;}
SignInNames                                   Property   System.Collections.Generic.List[Microsoft.Open.AzureAD.Model.SignInName] SignInNames {get;set;}
SipProxyAddress                               Property   string SipProxyAddress {get;}
State                                         Property   string State {get;set;}
StreetAddress                                 Property   string StreetAddress {get;set;}
Surname                                       Property   string Surname {get;set;}
TelephoneNumber                               Property   string TelephoneNumber {get;set;}
UsageLocation                                 Property   string UsageLocation {get;set;}
UserPrincipalName                             Property   string UserPrincipalName {get;set;}
UserState                                     Property   string UserState {get;set;}
UserStateChangedOn                            Property   string UserStateChangedOn {get;set;}
UserType                                      Property   string UserType {get;set;}

For example, you may also use “Select-Object *” to show all available properties of the users.

#View Azure AD/O365 All Users details including all properties 
Get-AzureADUser | Select-Object *
View Azure AD/O365 All Users details including all properties
View Azure AD/O365 All Users details including all properties

You can also filter the user details based on some criteria. For example, let’s get the user details which ‘Usage location’ is USA (US):

#View Azure AD/M365 Users details based on some criteria like 'US' 'Usage location' (as filter)
Get-AzureADUser | Where-Object {$_.UsageLocation -eq 'US'}
Office365 Azure AD
View Azure AD/M365 Users details based on some criteria

View Specific User through Office365 Azure AD

If you require specific O365 user details then just use a -ObjectId parameter and provide ObjectID or UserPrincipalName of the user:

#View Specific Office 365 User details
Get-AzureADUser -ObjectId [email protected]
Specific Office 365 User
Specific Office 365 User

Like the above example, you may use the user principal name in the place of Object ID, because it’s very hard to remember.

-Note

When we need to view all properties of a user, then use the below command:

#View Azure AD/M365 Specific User all properties info
Get-AzureADUser -ObjectId [email protected] | Select *
PS C:\> Get-AzureADUser -ObjectId [email protected] | Select *

ExtensionProperty              : {[odata.metadata, https://graph.windows.net/79ec0faf-7be8-4202-a758-c20f2d2127cd/$metadata#directoryObjects/@Element], [odata.type, Microsoft.DirectoryServices.User],  
                                 [createdDateTime, 2021-01-13 1:44:28 PM], [employeeId, ]...}
DeletionTimestamp              :
ObjectId                       : fbb5f0fa-fed0-4fea-a4df-559049b10175
ObjectType                     : User
AccountEnabled                 : True
AgeGroup                       :
AssignedLicenses               : {class AssignedLicense {
                                   DisabledPlans: System.Collections.Generic.List`1[System.String]
                                   SkuId: c42b9cae-ea4f-4ab7-9717-81576235ccac
                                 }
                                 }
AssignedPlans                  : {class AssignedPlan {
                                   AssignedTimestamp: 2021-02-08 8:10:25 AM
                                   CapabilityStatus: Enabled
                                   Service: SharePoint
                                   ServicePlanId: 5dbe027f-2339-4123-9542-606e4d348a72
                                 }
                                 , class AssignedPlan {
                                   AssignedTimestamp: 2021-02-08 8:10:25 AM
                                   CapabilityStatus: Enabled
                                   Service: MIPExchangeSolutions
                                   ServicePlanId: cd31b152-6326-4d1b-ae1b-997b625182e6
                                 }
                                 , class AssignedPlan {
                                   AssignedTimestamp: 2021-02-08 8:10:25 AM
                                   CapabilityStatus: Enabled
                                   Service: ProjectWorkManagement
                                   ServicePlanId: b737dad2-2f6c-4c65-90e3-ca563267e8b9
                                 }
                                 , class AssignedPlan {
                                   AssignedTimestamp: 2021-02-08 8:10:25 AM
                                   CapabilityStatus: Enabled
                                   Service: exchange
                                   ServicePlanId: 46129a58-a698-46f0-aa5b-17f6586297d9
                                 }
                                 ...}
City                           :
CompanyName                    : tho
ConsentProvidedForMinor        : 
Country                        :
CreationType                   :
Department                     : Finance
DirSyncEnabled                 :
DisplayName                    : Test User1
FacsimileTelephoneNumber       :
GivenName                      : Test
IsCompromised                  :
ImmutableId                    :
JobTitle                       :
LastDirSyncTime                : 
LegalAgeGroupClassification    :
Mail                           : [email protected]
MailNickName                   : TestUser1
Mobile                         :
OnPremisesSecurityIdentifier   :
OtherMails                     : {}
PasswordPolicies               :
PasswordProfile                : class PasswordProfile {
                                   Password: 
                                   ForceChangePasswordNextLogin: True
                                   EnforceChangePasswordPolicy: False
                                 }

PhysicalDeliveryOfficeName     :
PostalCode                     :
PreferredLanguage              :
ProvisionedPlans               : {class ProvisionedPlan {
                                   CapabilityStatus: Enabled
                                   ProvisioningStatus: Success
                                   Service: MicrosoftCommunicationsOnline
                                 }
                                 , class ProvisionedPlan {
                                   CapabilityStatus: Enabled
                                   ProvisioningStatus: Success
                                   Service: MicrosoftCommunicationsOnline
                                 }
                                 , class ProvisionedPlan {
                                   CapabilityStatus: Enabled
                                   ProvisioningStatus: Success
                                   Service: SharePoint
                                 }
                                 , class ProvisionedPlan {
                                   CapabilityStatus: Enabled
                                   ProvisioningStatus: Success
                                   Service: SharePoint
                                 }
                                 ...}
ProvisioningErrors             : {}
ProxyAddresses                 : {SMTP:[email protected]}
RefreshTokensValidFromDateTime : 2021-01-13 1:44:28 PM
ShowInAddressList              :
SignInNames                    : {}
SipProxyAddress                : [email protected]
State                          :
StreetAddress                  :
Surname                        : User1
TelephoneNumber                :
UsageLocation                  : US
UserPrincipalName              : [email protected]
UserState                      :
UserStateChangedOn             :
UserType                       : Member

You can also show selected customize property information of the user based on the requirement:

#View Azure AD/M365 Specific User selected properties info
Get-AzureADUser -ObjectId [email protected] | Select-Object ObjectID, DisplayName, Department, UsageLocation
Office365 Azure AD
Specific User selected properties info

Create a New User in Office365 Azure AD

The good part is to have a knowledge of PowerShell, you can easily adopt any new modules and start utilizing in your daily day to day task.

If you don’t know or remember the command then easily you can search with the help of the Get-Command command.

#Type related item like "user" to get all commands which have matching charcters in the commands

Get-Command *user*
Get-Help command
Get-Command example

Now you can use Get-Help command to get syntax with all parameters for a specific command.

# Get-Help command to get syntax and parameters details
Get-Help New-AzureADUser -Full

In the below screenshot, you may see many parameters are showing in syntax but only some parameters are required.

Office365 Azure AD
Get-Help command

likewise this approach, easily you may get the command details without worry to remember the commands.

Now let me explain below script to create a new Office 365 user.


#Specifies the user's password profile.
$PasswordProfile=New-Object -TypeName Microsoft.Open.AzureAD.Model.PasswordProfile
$PasswordProfile.Password = "fgtyhjj#$5g@@56"

#Create a AzureAD user account
New-AzureADUser `
    -DisplayName "Admin A" `
    -GivenName "Admin" `
    -SurName "A" `
    -UserPrincipalName [email protected] `
    -UsageLocation IN `
    -MailNickName Example `
    -PasswordProfile $PasswordProfile `
    -AccountEnabled $true

Firstly, we’ve created a new variable of $PasswordProfile of type “Microsoft.Open.AzureAD.Model.PasswordProfile” which store the user’s initial password in this script in an encrypted format.

You can’t set the password in plain text format due to security concern. Now you may set the desired password in $PasswordProfile.Password property.

#Specifies the user's password profile.
$PasswordProfile=New-Object -TypeName Microsoft.Open.AzureAD.Model.PasswordProfile
$PasswordProfile.Password = "fgtyhjj#$5g@@56"

After that you can use this -PasswordProfile variable value in parameter -PasswordProfile, so that you can share this password with new user to logon.

#Create a AzureAD user account
New-AzureADUser `
    -DisplayName "Admin A" `
    -GivenName "Admin" `
    -SurName "A" `
    -UserPrincipalName [email protected] `
    -UsageLocation IN `
    -MailNickName Example `
    -PasswordProfile $PasswordProfile `
    -AccountEnabled $true

Create multiple New Users in Office 365 Azure AD

Creating multiple users also possible the same way through Office365 Azure AD, only you’ve to use a for-each loop.

Firstly, you need to save the user details in a CSV format with required properties like below example:

Office365 Azure AD
Office365 New User Details

Now let’s use below script to create multiple user accounts easily:

#Create multiple New Users in Office 365 Azure AD
$PasswordProfile=New-Object -TypeName Microsoft.Open.AzureAD.Model.PasswordProfile
$PasswordProfile.Password = "fgtyhjj#$5g@@56"

#Get saved user details from CSV file
$UsersList = Import-Csv -Path "C:\Users\Test Lab\PowerShell Scripts\Manage AzureAD Users\users_details.csv"

#Use Foreach loop to take one user details
foreach ($user in $UsersList)
{
    New-AzureadUser `
        -DisplayName $User.DisplayName `
        -GivenName $User.FirstName `
        -SurName $User.LastName `
        -UserPrincipalName $User.UserPrincipalName `
        -UsageLocation $User.UsageLocation `
        -MailNickName $User.MailNickName `
        -PasswordProfile $PasswordProfile `
        -AccountEnabled $true `
}

Modify Office 365 User Details

You as an administrator will receive the request many times from the HR team or user to update user properties like City, Address, Usage Location etc…

You can use Set-AzureADUser command to update the details.

Let’s take an example of the below command where we’re updating the city files to Delhi for the single user [email protected]

# Change Properties of Single user accounts
Set-AzureADUser -ObjectId [email protected] -City "Delhi"

You can also update properties of multiple users based on any condition

#Change department of users which usage location is US
Get-AzureADUser | Where-Object {$PSItem.UsageLocation -eq 'US'} | Set-AzureADUser -Department 'Finance'

Block Office 365 User Account

Sometimes we get a request from management, IT Helpdesk or HR team to block some user temporary from logon on Office365 portal.

# Block Access to single User Account
Set-AzureADUser -ObjectId [email protected] -AccountEnabled $true

# Check the User's AccountEnabled status
Get-AzureADUser -ObjectId [email protected] | Select Displayname, AccountEnabled

Delete User Account through Office 365 Azure AD

You’ll also receive a request to delete some user account which has left the organization and not require.

# Remove Single Azure User account
Remove-AzureADUser -ObjectId [email protected]

Let’s suppose that we need to remove multiple user accounts which usage location is India. You can use below script to complete this task:

# Remove Multiple Azure Users accounts
$AllUsers = Get-AzureADUser | Where-Object {$PSItem.Usagelocation -eq 'IN'}

foreach ($user in $AllUsers)
{
    Remove-AzureADUser -ObjectId $user.UserprincipalName
}

Conclusion

As you learned now, how easily you can create, view, modify, block and delete single or multiple users accounts through Office365 Azure AD PowerShell. We’ve also used the new Azure Active Directory PowerShell for Graph module which Microsoft also recommend.

After learning this basic commands, you can also find many PowerShell scripts on https://www.powershellgallery.com to manage Microsoft Office 365 environment.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.