Thursday, 19 April 2018

How to: Add Mailbox Import Export Role in Office 365 using PowerShell

When you are in Exchange Online environment, you might have required (or asked) to assign "Mailbox Import Export Role" for some kind of mailbox operation, like importing PST files, delete messages from mailbox using Search-Mailbox cmdlet, restore deleted mails using Restore-RecoverableItems cmdlet, etc. When you import PST files without this role you will probably receive this error message: "Please add Mailbox Import Export role for use running import and check back in 60 minutes".

By default, the "Mailbox Import Export" role is not assigned to any role group, even to the Organization Management role group. Typically, you assign a role to a built-in/custom role group, or you can assign a role to a user, or a universal security group. In this post, I am going to share PowerShell script to find who has access to Mailbox Import Export role and how to assign this role to user, security group and existing build-in/custom role group.

Before proceed, run the following commands to load Exchange Online powershel module:
$o365Cred = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $o365Cred -Authentication Basic -AllowRedirection
Import-PSSession $Session

Summary:

Assign Mailbox Import Export role to user, security group and existing role group

Run the following command to assign the role for the individual user account.
New-ManagementRoleAssignment –Role "Mailbox Import Export" –User "user name"
Run the following command to set this role for the universal security group.
New-ManagementRoleAssignment –Role "Mailbox Import Export" –SecurityGroup "group name"
Use the below command to add this role to existing management role group.
New-ManagementRoleAssignment -Role "Mailbox Import Export" -SecurityGroup "Organization Management" -Name "Import Export Org Management"
Note: You have to create a new Exchange Online PowerShell session to get new role permissions.

Find who has access to Mailbox Import Export role

You can run the following command to find out who has the role already.
Get-ManagementRoleAssignment –Role "Mailbox Import Export" | FL RoleAssigneeName, Name
In the result, you may see the Organization Management role group even though you haven’t explicitly given the rights , this is because of the members of the Organization Management role group can delegate the "Mailbox Import Export" role to themselves and other groups or users.

Remove Management Role Assignment

If you want to remove the existing role assignment, first you have to find the name of the role assignment that you want to delete using the command Get-ManagementRoleAssignment and run the following powershell command to clear the existing role.
Remove-ManagementRoleAssignment "Import Export Org Management" -Confirm:$false
Read More...

Wednesday, 18 April 2018

Recover Deleted Office 365 Groups using PowerShell

Microsoft using Office 365 Group as a base service for other products like Planner, MS Teams, Yammer, etc... , so keeping its identity is very important. You might have deleted an O365 group without knowing its usage in other services, in this case you will also loose the group's dependent contents. If you soft-deleted the office 365 group, by default the deleted object retained for 30 days (retention period) and you can easily restore the group and its associated content within this retention period, after the retention period the group and its associated content will be permanently deleted and cannot be restored.

When a group is restored, the following group associated content also get recovered: Office 365 Group's Azure AD object and its properties, group SMTP address, Exchange Online shared inbox and calendar, SharePoint Online team site and files, OneNote notebook, Planner buckets and tasks, Microsoft Teams and other associated contents.

We can recover deleted unified groups using Restore-AzureADMSDeletedDirectory cmdlet from Azure AD PowerShell V2 module. Before proceed install Azure Active Directory PowerShell for Graph and run the below command to connect Azure AD PowerShell module:
Connect-AzureAD
Recovering a deleted office 365 group includes following two steps:

Find Id of the deleted office 365 group

Actually we need to pass the object Id of a deleted group to Restore-AzureADMSDeletedDirectory cmdlet, so we need to first get the object id of the deleted group that we want to restore.
Get-AzureADMSDeletedGroup
The above command retrieves all the soft deleted groups in a directory that are recoverable. You can also filter the groups by name using the parameter -SearchString.
Get-AzureADMSDeletedGroup -SearchString "Test Group"
After running any one of the above two commands , note down the Id of the office 365 group that you want to restore.

Restore the deleted office 365 group

Once you got the Id of the deleted group from the above step, you can just run the following command after replacing the Id parameter with your target group object Id.
Restore-AzureADMSDeletedDirectoryObject –Id <deleted group id>
If you believe there is no duplicate entries in the deleted groups with the same name, you can use the following commands to get the deleted group Id and recover the object in single execution.
$groupId = (Get-AzureADMSDeletedGroup -SearchString "Test Group").Id
Restore-AzureADMSDeletedDirectoryObject –Id $groupId
Once you run the above command, the restoring process will be completed in few minutes. Run the following powershell command to verify that the group has been restored successfully.
Get-AzureADGroup -ObjectID $groupId
Read More...

Monday, 16 April 2018

Recover Deleted Emails in Office 365 Mailbox using PowerShell

As an Administrator you might requested by an Outlook user to restore the deleted e-mail messages. In Office 365, you can search and restore the deleted items using Exchange Online Powershell cmdlets Get-RecoverableItems and Restore-RecoverableItems.

Before proceed, first we need to connect Exchange Online powershel module by running below commands:
$o365Cred = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $o365Cred -Authentication Basic -AllowRedirection
Import-PSSession $Session

Summary:


Permissions Required :

To run the cmdlets Get-RecoverableItems and Restore-RecoverableItems, you must have one of the Exchange RBAC roles with the "Mailbox Import Export Role" assigned. By default, this role isn't assigned to any role group. Typically, you assign a role to a built-in or custom role group. Or you can assign a role to a user, or a universal security group. The below example add the role to the Organization Management role group:
New-ManagementRoleAssignment -Name "Import_Export_Organization_Management" -SecurityGroup "Organization Management" -Role "Mailbox Import Export"
Note: You have to create a new Exchange Online PowerShell session to get new role permissions.

Restore deleted messages to their original folder location:

We can use the Restore-RecoverableItems cmdlet to restore each item to its original location and this cmdlet takes the same search parameters that you used to find items.
Restore-RecoverableItems -Identity "AlexW" -SourceFolder RecoverableItems -SubjectContains "Important”

Restore deleted messages from bulk users mailbox:

You can use the below powershell commands if you want restore deleted emails from set of users' mailbox by importing user details from CSV file.
Import-Csv 'C:\Users.csv' | ForEach-Object {
$mailbox = $_."UserPrincipalName"
Write-Host "Recovering messages for" $mailbox -Foreground Yellow
Restore-RecoverableItems -Identity $mailbox -SourceFolder RecoverableItems -SubjectContains "Important" -FilterItemType Ipm.Note
}
Read More...

Tuesday, 27 March 2018

Add Secondary Site Administrator to OneDrive for Business Users using PowerShell

As an Office 365 Admin, in some situations you might need to gain access to users' OneDrive for Business site when some users are terminated and if they are marked for deletion . By default, each user is added as primary & secondary site collection administrators to their personal OneDrive site, so you have to add your account as secondary admin in the requiresd user's OneDrive site to gain full access.

In this post, I am going to explain how to add secondary admin for single OneDrive user's site and for all users OneDrive for Business (ODFB) sites using PowerShell. Before proceed install SharePoint Online Management Shell.

Summary:


Add Site Administrator for single user's OneDrive site:

Run the below powershell commands after replacing the variable <tenant name> with your Office 365 tenant name in all the occurrences, set the required user's OneDrive site url (you can copy your own OneDrive Site url and just replace your name with the required username) and provide global admin credentials.
# Specify your organization admin central url 
$AdminURI = "https://<tenant name>-admin.sharepoint.com"
 
# Specify Office 365 global admin in your organization
$AdminAccount = "admin@<tenant name>.onmicrosoft.com"
$AdminPass = "admin_password"

# Specify the secondary admin account 
$secondaryAdmin = "username@<tenant name>.onmicrosoft.com"
# Specify the target user's OneDrive Url. You can copy your OneDrive Site url and just replace your name with the required username.
$oneDriveSiteUrl = "https://<tenant name>-my.sharepoint.com/personal/<username>_<tenant name>_onmicrosoft_com/" 
 
$sstr = ConvertTo-SecureString -string $AdminPass -AsPlainText -Force
$AdminPass = ""
$UserCredential = New-Object System.Management.Automation.PSCredential -argumentlist $AdminAccount, $sstr
 
Connect-SPOService -Url $AdminURI -Credential $UserCredential
Set-SPOUser -Site $oneDriveSiteUrl -LoginName $secondaryAdmin -IsSiteCollectionAdmin $true -ErrorAction SilentlyContinue
Write-Host "Secondary site admin added successfully"

Set Secondary Site Collection Admin for all OneDrive for Business sites

To give admin access for all OneDrive profiles, first we need to find list of users with OneDrive feature provisioned by using SharePoint Online UserProfileService and we can grant administrator access for all OneDrive sites by using the Set-SPOUser cmdlet.
# Specify your organization admin central url 
$AdminURI = "https://<tenant name>-admin.sharepoint.com"

# Specify the secondary admin account 
$secondaryAdmin = "username@<tenant name>.onmicrosoft.com"
 
# Specify the User account for an Office 365 global admin in your organization
$AdminAccount = "admin@<tenant name>.onmicrosoft.com"
$AdminPass = "admin_password"
 
$loadInfo1 = [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client")
$loadInfo2 = [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime")
$loadInfo3 = [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.UserProfiles")
 
$sstr = ConvertTo-SecureString -string $AdminPass -AsPlainText -Force
$AdminPass = ""
$creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($AdminAccount, $sstr)
$UserCredential = New-Object System.Management.Automation.PSCredential -argumentlist $AdminAccount, $sstr
 
# Add the path of the User Profile Service to the SPO admin URL, then create a new webservice proxy to access it
$proxyaddr = "$AdminURI/_vti_bin/UserProfileService.asmx?wsdl"
$UserProfileService= New-WebServiceProxy -Uri $proxyaddr -UseDefaultCredential False
$UserProfileService.Credentials = $creds
 
# Set variables for authentication cookies
$strAuthCookie = $creds.GetAuthenticationCookie($AdminURI)
$uri = New-Object System.Uri($AdminURI)
$container = New-Object System.Net.CookieContainer
$container.SetCookies($uri, $strAuthCookie)
$UserProfileService.CookieContainer = $container
 
# Sets the first User profile, at index -1
$UserProfileResult = $UserProfileService.GetUserProfileByIndex(-1)
Write-Host "Starting- This could take a while."
$NumProfiles = $UserProfileService.GetUserProfileCount()
$i = 1
 
Connect-SPOService -Url $AdminURI -Credential $UserCredential
 
# As long as the next User profile is NOT the one we started with (at -1)...
While ($UserProfileResult.NextValue -ne -1) 
{
Write-Host "Checking profile $i of $NumProfiles"
# Look for the Personal Space object in the User Profile and retrieve it
# (PersonalSpace is the name of the path to a user's OneDrive for Business site. 
# Users who have not yet created a  OneDrive for Business site might not have this property)
$Prop = $UserProfileResult.UserProfile | Where-Object { $_.Name -eq "PersonalSpace" } 
$Url= $Prop.Values[0].Value
  
# If "PersonalSpace" exists, then OneDrive Profile provisioned for the user...
if ($Url) {
$oneDriveSiteUrl = "https://<tenant name>-my.sharepoint.com"+ $Url.Substring(0,$Url.Length-1)
 
# Set the secondary admin
Set-SPOUser -Site $oneDriveSiteUrl -LoginName $secondaryAdmin -IsSiteCollectionAdmin $true -ErrorAction SilentlyContinue
Write-Host "Site admin added successfully: "$oneDriveSiteUrl 
}
# And now we check the next profile the same way...
$UserProfileResult = $UserProfileService.GetUserProfileByIndex($UserProfileResult.NextValue)
$i++
}
Read More...

Friday, 23 March 2018

How to Change UPN/Sign-In Name of Office 365 user using PowerShell

In Office 365 cloud world, users need to use their UPN (UserPrincipalName) as main login name to sign-in into any Office 365 apps. In some situations, we need to change the UPN for some users either to match the UPN with users' primary email address or if users are created with UPN that ends-with .onmicrosoft.com (user@domain.onmicrosoft.com).

In this post, I am going to share powershell script to modify userprincipalname of an user and update upn for bulk azure ad users from CSV. We can use Set-AzureADUser cmdlet to modify user properties and this cmdlet belongs to Azure AD V2 PowerShell module.

Note: Before proceed install Azure Active Directory PowerShell for Graph and run the below command to connect Azure AD V2 PowerShell module:
Connect-AzureAD

Rename Office 365 user/change user name part in UPN:

You can run the following command to change the username part in required user's UPN and you can also use the same commands to modify domain name of an user.
$old_upn= "morgank@contoso.com"
$new_upn= "morgankevin@contoso.com"
Set-AzureADUser -ObjectId $old_upn -UserPrincipalName $new_upn

Change UPN to match primary Email address for Bulk users from CSV:

In many places, even though Office 365 service login UI asks email address, we should type the UPN of the user for successful login, unless the user's login name (UserPrincipalName) and primary SMTP (Email address) match with each other. So to avoid confusion from end-users, we need to ensure UPN of an user should match with the user's primary SMTP e-mail address.

You can use the below powershell script to update UPN of bulk users by importing users and their new upn (EmailAddress) from csv file.
Import-Csv 'C:\Office365Users.csv' | ForEach-Object {
$upn = $_."UserPrincipalName"
$newupn = $_."EmailAddress"
Write-Host "Changing UPN value from: "$upn" to: " $newupn -ForegroundColor Yellow
Set-AzureADUser -ObjectId $upn  -UserPrincipalName $newupn
}
Note: Your csv file (Office365Users.csv) should includes the column headers UserPrincipalName and EmailAddress (New UPN), if you have different headers you need to modify the above script accordingly.

Change domain name for bulk users:

In some cases, after migrating users from On-Premise Active Directory using DirSync, new Office 365 users are created with Primary UPN that ends with domain part as .onmicrosoft.com (Ex: user@domain.onmicrosoft.com). In this case, we can use the below script to modify upn with actual domain name.
$domain = "MTS.com"
Get-AzureADUser -All $True | Where { $_.UserPrincipalName.ToLower().EndsWith("onmicrosoft.com") } |
ForEach {
 $newupn = $_.UserPrincipalName.Split("@")[0] + "@" + $domain
 Write-Host "Changing UPN value from: "$_.UserPrincipalName" to: " $newupn -ForegroundColor Yellow
 Set-AzureADUser -ObjectId $_.UserPrincipalName  -UserPrincipalName $newupn
}

Export Users New UserPrincipalName details to CSV:

Once you changed the main login name of an user using any of the above methods, you can just check it by running the below command
Get-AzureADUser -ObjectId "morgan@contoso.com" | Select DisplayName, UserPrincipalName
You can also export all azure ad users detail to csv file by running below command
Get-AzureADUser -All $True | Select DisplayName, UserPrincipalName |
Export-CSV "C:\\O365Users.csv" -NoTypeInformation -Encoding UTF8
Read More...

Tuesday, 20 March 2018

UserPrincipalName (UPN) vs Email address - In Azure AD Login / Office 365 Sign-in

In the Windows On-Premises Active Directory, users can either use samAccountName or User Principal Name (UPN) to login into AD based service. The User Principal Name is basically the ID of the user in Active Directory and sometimes it might not be same as users’ email, but users won't face many problems due to this email and UPN mis-match as users only use this identity in local AD environment.

In Office 365 cloud environment, you should care about the mismatch of UPN and Email address. Office 365 also does not force that users’ email match with userPrincipalName and most of us (Office 365 Admins) know that logging into the Office 365 portal is based on the LoginID/UPN not the E-mail of the user.

In many places, even though Office 365 service login UI asks email address, we should type the userPrincipalName of the user for successful login, unless the user's UPN and Primary SMTP (Email address) match with each other.

UPN vs Primary SMTP address

As you’ll see above, there are some login prompts say that “enter your email address” but in fact, you need to use UPN. In this situation, you may want to consider making user's UPN as an alternate email address on their account but this also won’t help them login.

As Office 365 Login UI itself confuse what should user enter as login identity and also end-users do not know much about UPN as they use their e-mail address in most cases, so now you can understand the importance of why the UPN of an user should match with the user's primary SMTP address (e-mail address).

You can refer the following good posts to know more about:
Read More...

Friday, 16 March 2018

Find Office 365 users with a specific license type using PowerShell

We may fall in a situation to get a list of Office 365 users with a specific license plan to decide license usage or some other need. We can easily find users who has a specific office 365 license feature using Azure AD Powershell commands.

Before proceed, first run the below command to connect Azure AD Powershell module.
Import-Module MSOnline
Connect-MsolService
We can run Get-MsolAccountSku cmdlet to get a list of the available licenses in your Office 365 tenant.
Get-MsolAccountSku
Export Office 365 users based on a specific license plan

Once run the above command, copy the the AccountSkuId value for the license that you want to filter.

Now copy the below script and replace AccountSkuId of license that you copied from the above step and run the modified script to list users who are assigned to a specific license in Office 365.
Get-MsolUser -All | Where-Object {($_.licenses).AccountSkuId -eq "tenant:EMSPREMIUM"}

Export list of users who has a specific license to CSV file.

Run the below command to export office 365 users based on required or selected license plan.
Get-MsolUser -All | Where-Object {($_.licenses).AccountSkuId -eq "tenant:EMSPREMIUM"} |
Select-Object UserPrincipalName, DisplayName |
Export-Csv "C:\O365Users.csv"  -NoTypeInformation -Encoding UTF8
Read More...

Thursday, 15 March 2018

Migrate Distribution Groups to Office 365 Groups using O365 Admin Center

For very long years every organizations using distribution lists to communicate and collaborate with group of people both inside and outside the organization. Now in cloud environment, Office 365 Groups provides more powerful solution for team collaboration along with the same features of distribution list. In this post, I am going to share the easy steps to convert/upgrade distribution lists to office 365 groups.

Note: You must have a privilege of Office 365 global admin or Exchange admin to upgrade a distribution list.

Steps to Convert Bulk Distribution Lists to Office 365 Groups:

  • In the left navigation, expand Admin center, and then select Exchange.
Migrate Bulk Distribution Lists to Office 365 Groups
  • In the Exchange admin center, under recipients, select groups
Convert Bulk Distribution Groups to Office 365 Groups

  • Now you can see Upgrade Distribution Groups option with the message "You have distribution lists that are eligible for upgrade". Click the Get Started button to proceed next.
convert distribution group to unified group

  • Now you can see the Bulk Upgrade page,  select the required distribution lists that you want to upgrade and click Start Upgrade button as shown in below image. 
Upgrade Bulk Distribution Groups to Office 365 Groups

  • In the next dialog, choose OK to confirm the upgrade and the process begins immediately. Depending on the size and number of distribution groups that you selected, the process can take minutes or hours.
Read More...