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

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

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
}

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++
}

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

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:

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

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.

Wednesday, 14 March 2018

Steps to Restore Deleted Office 365 Groups using Office 365 Admin Center

Microsoft forcing Office 365 Group as a base service for other office 365 services like Planner, MS Teams, Yammer, etc... As O365 group becomes a core feature, keeping its identity is very important. When you delete (soft-delete) an Office 365 group, by default the deleted group retained for 30 days. After 30 days, the group and its associated its content will be permanently deleted and cannot be restored.

When a group is restored, the following content also restored:
  • Azure Active Directory (AD) Office 365 Group object and its properties.
  • Group SMTP address.
  • Exchange Online shared inbox and calendar.
  • SharePoint Online team site and files.
  • OneNote notebook.
  • Planner buckets, tasks. etc...
  • Microsoft Team or Office 365 Connected Yammer group, and its related content.

Follow the below steps to recover deleted O365 group:

  • In the left navigation, expand Admin center, and then select Exchange.
office 365 restore deleted office 365 group
  • In the Exchange admin center, under recipients, select groups
restore deleted unified group
  • Now you can see all groups and its active status. 
  • You can sort the groups by clicking the column header Status and see soft deleted groups on top. If the group has been permanently deleted, it won't be listed here.
  • Select the deleted group that you want to restore and you can view delete time info in the right pane. 
  • Now choose the Restore icon to recover the selected group. 
how to restore or recover deleted office 365 group

  • Finally click Refresh icon to update the reports page and you can see the restored group will show as Active.

Friday, 2 March 2018

Bool Value Check with IF Statement and Where Object in PowerShell

In PowerShell script, we often use logic to check some value is true or false. In normal case we may need to check if a value is true or not with If statement and in some other cases we may required to compare bool value property in Where object to filter array of values based on some Boolean value attribute.

Bool Check in If Statement:

Example 1:
$a = 10; $b = 5;
$result = ($a -gt $b);
if($result -eq $true) {
  Write-Host -ForegroundColor GREEN "TRUE"
} else {
  Write-Host -ForegroundColor RED   "FALSE"
}
Example 2:
$a = 10; $b = 5;
$result = ($a -gt $b);
if($result) {
  Write-Host -ForegroundColor GREEN "TRUE"
}
Example 3: Inverse bool check
$a = 10; $b = 5;
$result = ($a -lt $b);
if(-not ($result))  {
  Write-Host -ForegroundColor GREEN "TRUE"
}

Boolean Check in Where Object Filter:

Example 1:
$Result=@() 
1..25 | ForEach-Object {
$Result += New-Object PSObject -property @{ 
ID = $_
Status = if (-not($_ % 2)){$true} else {$false}
}}

// Example 1:
$Result | Where {$_.Status -eq $true}

// Example 2:
$Result | Where {$_.Status}

// Example 3: Inverse boolean check
$Result | Where {-not ($_.Status)}

Tuesday, 27 February 2018

How to download Microsoft Azure Active Directory Authentication Library (ADAL)

The Azure Active Directory Authentication Library (ADAL) enables client application developers to authenticate users to cloud Azure AD or on-premises Active Directory (AD), and obtain tokens for securing API calls.

There are three main features in ADAL:
  • ADAL supports the automatic refreshment of tokens after they reach their expiration;
  • It also supports asynchronous methods that require tokens.
  • ADAL can manage the process of getting tokens and, by default, stores tokens in what Microsoft calls an "in-memory token cache."

How to download Microsoft.IdentityModel.Clients.ActiveDirectory dll from Nuget:

How to download Microsoft.IdentityModel.Clients.ActiveDirectory dll from Nuget

  • Find the file in File Explorer and change its file extension from .nupkg to .zip.
  • Right-click the .zip file and choose Extract All. Choose Extract. You'll end up with an unzipped folder entitled "Microsoft.Identitymodel.Clients.Activedirectory.version_no".

Thursday, 22 February 2018

Check if Office 365 User is Licensed or Not using PowerShell

In this post I am going to write PowerShell script to check if a given office 365 user is licensed or not using Azure AD V2 PowerShell cmdlet Get-AzureADUser. Earlier with Old Azure AD V1 powershell command (Get-MsolUser) we had the attribute isLicensed but we don't have the same property in latest V2 PowerShell module, so we need to use the property AssignedLicenses to check license status.

Note: Before proceed install Azure Active Directory PowerShell for Graph and run the below command to connect Azure AD V2 PowerShell module:
Connect-AzureAD
The below command checks if license is provisioned or not for the given user account:
$user = "username@o365domain.com"
$AssignedLicenses = (Get-AzureADUser -ObjectId $user).AssignedLicenses
If ($AssignedLicenses.Count -ne 0) {
      Write-Host "Licensed"
 } Else {
        Write-Host "Not licensed"
}

Export all licensed users to CSV file:

Run the below commands to export all the licensed office 365 users to csv file.
$Result=@() 
Get-AzureADUser -All $True | ForEach-Object {
if($_.AssignedLicenses.Count -ne 0){
$Result += New-Object PSObject -property @{ 
Name = $_.DisplayName
UserPrincipalName = $_.UserPrincipalName }
}}
$Result | Export-CSV "C:\\LicensedO365Users.csv" -NoTypeInformation -Encoding UTF8

Export all Unlicensed users to CSV file:

Run the below powershell commands to export all the office 365 users whose license is not provisioned.
$Result=@() 
Get-AzureADUser -All $True | ForEach-Object {
if($_.AssignedLicenses.Count -eq 0){
$Result += New-Object PSObject -property @{ 
Name = $_.DisplayName
UserPrincipalName = $_.UserPrincipalName }
}}
$Result | Export-CSV "C:\\UnLicensedO365Users.csv" -NoTypeInformation -Encoding UTF8

Export license status of all Office 365 users:

$Result=@() 
Get-AzureADUser -All $True | ForEach-Object {
$IsLicensed = ($_.AssignedLicenses.Count -ne 0)
$Result += New-Object PSObject -property @{ 
Name = $_.DisplayName
UserPrincipalName = $_.UserPrincipalName
IsLicensed = $IsLicensed  }
}
$Result | Export-CSV "C:\\O365UsersLicenseStatus.csv" -NoTypeInformation -Encoding UTF8

Check license status for bulk users from CSV file:

The below command checks whether license is applied or not for bulk azure ad users by importing users from CSV file and export the result to csv file.
$Result=@() 
Import-Csv 'C:\Users.csv' | ForEach-Object {
$user = $_."UserPrincipalName"
$userObj = Get-AzureADUser -ObjectId $user
$IsLicensed = ($userObj.AssignedLicenses.Count -ne 0)
$Result += New-Object PSObject -property @{ 
Name = $userObj.DisplayName
UserPrincipalName = $userObj.UserPrincipalName
IsLicensed = $IsLicensed }
}
$Result | Export-CSV "C:\\LicenseStatusReport.csv" -NoTypeInformation -Encoding UTF8

Wednesday, 21 February 2018

Export Enabled and Disabled Office 365 Users to CSV using PowerShell

In this post I am going to share PowerShell script to export enabled Azure AD users and disabled (sign-in blocked) users to CSV file by using latest Azure AD PowerShell for Graph. With latest Azure AD PowerShell module we can extract Office 365 users information by using Get-AzureADUser cmdlet, this command includes the property AccountEnabled and it indicates whether the user is enabled or disabled.

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

Export Enabled Office 365 Users to CSV:

The below command lists all the enabled Azure AD users in PowerShell console.
Get-AzureADUser -All $True | Where-Object { $_.AccountEnabled -eq $true } | FT
You can export user details to csv file by running below command:
Get-AzureADUser -All $True | Where-Object { $_.AccountEnabled -eq $true } |
Select-Object UserPrincipalName, DisplayName, Department |
Export-Csv "C:\EnabledO365Users.csv"  -NoTypeInformation -Encoding UTF8

Export Disabled Office 365 Users to CSV:

Run the below command to list disabled or sign-in access blocked office 365 users in PowerShell console.
Get-AzureADUser -All $True | Where-Object { $_.AccountEnabled -eq $false } | FT
You can get a list of disabled office 365 users in csv file by running below command:
Get-AzureADUser -All $True | Where-Object { $_.AccountEnabled -eq $false } |
Select-Object UserPrincipalName, DisplayName, Department |
Export-Csv "C:\DisabledO365Users.csv"  -NoTypeInformation -Encoding UTF8

Tuesday, 13 February 2018

Check if Office 365 User is Blocked or Not using PowerShell

In this post I am going to share PowerShell script to check if a given office 365 user is blocked to sign-in by using latest Azure AD PowerShell for Graph. We can use Get-AzureADUser cmdlet to get office 365 user information, this command returns the property AccountEnabled and it indicates whether the login status of user is enabled or disabled. Earlier with Old Azure AD powershell command (Get-MsolUser) we had the same attribute with different name BlockCredential.

Before proceed install Azure Active Directory PowerShell for Graph and run the below command to connect Azure AD PowerShell module:
Connect-AzureAD
The below command checks if login status is enabled or blocked for the given azure ad user account:
$user = "username@o365domain.com"
$accountEnabled = (Get-AzureADUser -ObjectId $user).AccountEnabled
If ($accountEnabled) {
      Write-Host "$user enabled"
 } Else {
        Write-Host "$user disabled"
}

Check sign-in status of multiple user accounts:

Use the below command to check sign-in status is enabled or blocked for multiple user accounts:
$users = "user1@o365domain.com","user1@o365domain.com"
ForEach ($user in $users) {
$accountEnabled = (Get-AzureADUser -ObjectId $user).AccountEnabled
If ($accountEnabled) {
      Write-Host "$user enabled"
 } Else {
        Write-Host "$user disabled"
}}

Check account status for bulk users from CSV file:

The below command gets account status for bulk azure ad users by importing users from CSV file and export the result to csv file.
$Result=@() 
Import-Csv 'C:\Users.csv' | ForEach-Object {
$user = $_."UserPrincipalName"
$userObj = Get-AzureADUser -ObjectId $user
$Result += New-Object PSObject -property @{ 
Name = $userObj.DisplayName
UserPrincipalName = $userObj.UserPrincipalName
AccountEnabled = $userObj.AccountEnabled }
}
$Result | Export-CSV "C:\\AccountStatusReport.csv" -NoTypeInformation -Encoding UTF8

Export all Azure AD users account status to CSV file:

The below command gets all office 365 users and exports account enabled status to csv file.
$Result=@() 
Get-AzureADUser -All $True | ForEach-Object {
$Result += New-Object PSObject -property @{ 
Name = $_.DisplayName
UserPrincipalName = $_.UserPrincipalName
AccountEnabled = $_.AccountEnabled }
}
$Result | Export-CSV "C:\\AccountStatusReport.csv" -NoTypeInformation -Encoding UTF8

Thursday, 8 February 2018

Check if a Software Program Is Installed using PowerShell Script

We can easily check the list of installed applications via Control Panel's Add or Remove Programs UI. But if you are System Administrator and need to frequently check whether an application is installed or not, the PowerShell script will be very useful in this case.

Summary:


Check if a Software is installed by using WMI query:

The below function checks the application is installed or not by using Powershell's WMI Class Win32_Product.
function Check_Program_Installed( $programName ) {
$wmi_check = (Get-WMIObject -Query "SELECT * FROM Win32_Product Where Name Like '%$programName%'").Length -gt 0
return $wmi_check;
}

Check_Program_Installed("Microsoft SQL")

Check if a Program is installed or not by checking registry value:

The below PowerShell function check the Uninstall location and returns true if a given program is installed and returns false if not installed.
function Check_Program_Installed( $programName ) {
$x86_check = ((Get-ChildItem "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall") |
Where-Object { $_."Name" -like "*$programName*" } ).Length -gt 0;

if(Test-Path 'HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall')  
{
$x64_check = ((Get-ChildItem "HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall") |
Where-Object { $_."Name" -like "*$programName*" } ).Length -gt 0;
}
return $x86_check -or $x64_check;
}

Check_Program_Installed("Microsoft")
This above script checks both the regular Uninstall location as well as the"Wow6432Node" location to ensure that both 32-bit and 64-bit locations are checked for software installations.

Check if a Software is installed in Remote Machine:

The below function checks if the given software program is installed or not in remote computer.
function Check_Program_Installed($computer, $programName ) {
$wmi_check = (Get-WMIObject -ComputerName $computer -Query "SELECT * FROM Win32_Product Where Name Like '%$programName%'").Length -gt 0
return $wmi_check;
}

Check_Program_Installed("hp-pc","Microsoft SQL")

Export list of Installed Software Programs into CSV file:

You can export the installed software application details to CSV using Powershell's Export-CSV cmdlet. The following script exports the Non-Microsoft applications to CSV file.
Get-WMIObject -Query "SELECT * FROM Win32_Product Where Not Vendor Like '%Microsoft%'" |
Select-Object Name,Version,Vendor,InstallLocation,InstallDate |
Export-CSV 'C:\Non_MS_Products.csv'

Friday, 19 January 2018

Remove user from local Administrator group using PowerShell

In this post I am going to share PowerShell script to remove local user account or AD domain users from local Administrators group.

Remove user account from local Administrators group :

The following powershell commands remove the given AD user account from local Admins group.
$user = "DomainName/Morgan";
$group = "Administrators";
$groupObj =[ADSI]"WinNT://./$group,group" 
$userObj = [ADSI]"WinNT://$user,user"
$groupObj.Remove($userObj.Path)
If you want to remove non-domain local user account, you need to just pass the username as shown below:
$user = "ComputerName/Morgan";

Remove multiple users from local Administrators group :

Use the below PowerShell script to remove set of Active Directory user accounts from local Admins group. First create the text file users.txt which includes one user name in each line.
$group = "Administrators";
$groupObj =[ADSI]"WinNT://./$group,group" 
ForEach ($user in (Get-Content "C:\users.txt"))
{
   $userObj = [ADSI]"WinNT://$user,user"
   $groupObj.Remove($userObj.Path)
}

Remove user from local Admins group on Remote computer :

We need to provide the remote computer name to remove local Administrators group member on a remote computer.
$computer = "hp-pc";
$domainUser = "DomainName/Morgan";
$groupObj =[ADSI]"WinNT://$computer/Administrators,group" 
$userObj = [ADSI]"WinNT://$domainUser,user"
$groupObj.Remove($userObj.Path)

Thursday, 18 January 2018

PowerShell : Add a user to the local Administrators group

By default the local Administrators group will be reserved for local admins. However, in some cases, you might want to grant an end user administrator privileges on his machine so that he can able to install a driver or an application, in this case we can easily use PowerShell commands to add local user or AD domain users to local Administrators group in local machine and remote computer.

Add a user account to the local Administrators group :

The following powershell commands add the given user account to local Admin group.
$user = "ComputerName/Morgan";
$group = "Administrators";
$groupObj =[ADSI]"WinNT://./$group,group" 
$userObj = [ADSI]"WinNT://$user,user"
$groupObj.Add($userObj.Path)

Add a AD domain user account to the local Admin group :

We can use the above same commands to add domain user account by just passing the domain user.
$domainUser = "DomainName/Morgan";
$group = "Administrators";
$groupObj =[ADSI]"WinNT://./$group,group" 
$userObj = [ADSI]"WinNT://$domainUser,user"
$groupObj.Add($userObj.Path)

Add a domain user account to the local Administrators group on a Remote computer:

We need to just pass the remote machine name to add an Active Directory user to the local Administrators group on a remote Windows computer with PowerShell.
$computer = "hp-pc";
$domainUser = "DomainName/Morgan";
$group = "Administrators";
$groupObj =[ADSI]"WinNT://$computer/$group,group" 
$userObj = [ADSI]"WinNT://$domainUser,user"
$groupObj.Add($userObj.Path)

Fix: The Security database on the server does not have a computer account for this workstation trust relationship

Problem :

Users might have received following error when they attempting to log on to a Active Directory domain joined machine.
The Security database on the server does not have a computer account for this workstation trust relationship

Fix/Solution :

Usually this error occurs if the problematic computer object in AD is disabled or deleted. You can either dis-join and re-join or reset the problematic computer object in AD if you have required Admin access.

Also check whether your local machine time is synced with DC server.

If you can't resolve the issue using above stated method, you can follow the below steps:
  1. Open ADUC console (Active Directory Users and Computers)
  2. Click the menu View and make sure that Advanced Features is checked.
  3. Navigate to the organizational unit (OU) where the the problematic computer account resides.
  4. Open the Properties for the computer object
  5.  Choose the Attribute Editor tab in the Properties dialog box
  6. Check the attributes dNSHostName & servicePrincipalName and make sure that the entry matches the host name that you have configured in your problem computer object (Start -> Computer -> Properties -> Full Computer Name)
    dNSHostName:
    computername.domainname.com
    
    servicePrincipalName:
    HOST/computername.domainname.com
    If you find that both entries are not matched, you can change the correct value.
  7. Restart the computer to reflect changes quickly and try to login again.

Tuesday, 9 January 2018

Search Office 365 Mailbox : Delete, Copy and Move Messages using PowerShell

In this post I am going to share PowerShell script to search mailbox and delete, copy and move searched messages from one mailbox to another mailbox. We can use the exchange powershell cmdlet Search-Mailbox to search a mailbox and copy the results to a specified target mailbox and this cmdlet is available for both Exchange On-Premises and Exchange Online environment.

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:


Delete searched messages from mailbox

To delete messages we need to use DeleteContent switch, to use the DeleteContent switch you have to be assigned the Mailbox Import Export management role. 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.

This example searches Alex Wilber's mailbox for messages that contain the phrase "test message" in the subject and deletes the messages from the source mailbox.
Search-Mailbox -Identity "Alex Wilber" -SearchQuery {Subject:"test message" } -DeleteContent

Copy messages between mailboxes

This example searches Alex Wilber's mailbox for messages that contain the subject "sales report" in the subject and copy the result messages to Allan Deyoung's mailbox in the target folder "Sales".
Search-Mailbox -Identity "Alex Wilber" -SearchQuery {Subject:"sales report" } -TargetMailbox "Allan Deyoung" -TargetFolder "Sales"

Move messages from source mailbox to target mailbox

Move operation is nothing but the copy action along with removing messages from source mailbox. This example search and move messages from Alex Wilber's mailbox to Allan Deyoung's mailbox.
Search-Mailbox -Identity "Alex Wilber" -SearchQuery {Subject:"sales report" } -TargetMailbox "Allan Deyoung" -TargetFolder "Sales" -DeleteContent

Friday, 5 January 2018

Connect to Microsoft Graph API using PowerShell

In this article I will explain how to connect to Microsoft Graph and query current user information from Azure AD. To call Microsoft Graph, we must first acquire an access token from Azure Active Directory (Azure AD), we can get access token either using registered Azure AD application or by using well known Azure AD clients (Ex: PowerShell).

Pre-requisites

We are going to get access token by using AuthenticationContext.AquireToken method from the Active Directory Authentication Library (ADAL). To use ADAL library we need to install Azure Resource Manager PowerShell. If your main OS is Windows 10, and if you have PowerShellGet installed, you can run the following command to install the Azure Resource Manager PowerShell module.
Install-Module AzureRM -SkipPublisherCheck -AllowClobber -Force

Function - GetAccessToken

Instead of creating a new Client Id and Azure AD application, here we are using a well know Client Id reserved for PowerShell: 1950a258-227b-4e31-a9cf-717495945fc2.
Function GetAccessToken
   {
    param (        
        [Parameter(Position=0, Mandatory=$false)] 
        [string] $Office365Username, 
        [Parameter(Position=1, Mandatory=$false)] 
        [string] $Office365Password
      )
    # Add ADAL (Microsoft.IdentityModel.Clients.ActiveDirectory.dll) assembly path from Azure Resource Manager SDK location
    Add-Type -Path "C:\Program Files (x86)\Microsoft SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\AzureRM.Profile\Microsoft.IdentityModel.Clients.ActiveDirectory.dll"
    # or simply import AzureRm module using below command
    # Import-Module AzureRm
    #PowerShell Client Id. This is a well known Azure AD client id of PowerShell client. You don't need to create an Azure AD app.
    $clientId = "1950a258-227b-4e31-a9cf-717495945fc2"
    $redirectUri = "urn:ietf:wg:oauth:2.0:oob"
    $resourceURI = "https://graph.microsoft.com"
    $authority = "https://login.microsoftonline.com/common"
    $authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority
    
    if (([string]::IsNullOrEmpty($Office365Username) -eq $false) -and ([string]::IsNullOrEmpty($Office365Password) -eq $false)) 
    { 
    $SecurePassword = ConvertTo-SecureString -AsPlainText $Office365Password -Force            
    #Build Azure AD credentials object  
    $AADCredential = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.UserCredential" -ArgumentList $Office365Username,$SecurePassword
    # Get token without login prompts.
    $authResult = $authContext.AcquireToken($resourceURI, $clientId,$AADCredential)
    } 
    else 
    {     
    # Get token by prompting login window.
    $authResult = $authContext.AcquireToken($resourceURI, $clientId, $redirectUri, [Microsoft.IdentityModel.Clients.ActiveDirectory.PromptBehavior]::Always)
    } 
    return $authResult.AccessToken
}

Connect and Fetch data from Azure AD using Rest API :

Once you get the required access token you can easily query graph api using Invoke-RestMethod cmdlet by passing access token.

Get Access Token : The below command gets required access token with login prompts.
$accessToken= GetAccessToken
Get Access Token by passing credentials without login prompts:
$accessToken= GetAccessToken -Office365Username "admin@tenant.onmicrosoft.com" -Office365Password "admin_pwd"
Example 1: The below command gets the current user profile details.
$apiUrl = "https://graph.microsoft.com/v1.0/me"
$myPrfoile = Invoke-RestMethod -Headers @{Authorization = "Bearer $accessToken"} -Uri $apiUrl -Method Get
Example 2: The below command gets all the Azure AD user details.
$apiUrl = "https://graph.microsoft.com/v1.0/users"
$users = Invoke-RestMethod -Headers @{Authorization = "Bearer $accessToken"} -Uri $apiUrl -Method Get

Thursday, 4 January 2018

Convert Office 365 Group as Public or Private

When you create an Office 365 group, you can choose the group type as public or private. Previously in Office 365, you can't change the privacy setting once you created the group. Now, you can change the privacy settings using PowerShell or OWA.

Method 1: Convert Office 365 Groups privacy setting using PowerShell

We can use the Exchange Online powershell cmdlet Set-UnifiedGroup to modify an Office 365 Group. The below example changes the Office 365 Group named "Sales Department" from a public group to a private group.
Set-UnifiedGroup -Identity "Sales Department" -AccessType Private
The below example converts a private group to public group.
Set-UnifiedGroup -Identity "Sales Department" -AccessType Public

Method 2: Change an Office 365 Group's privacy type from OWA

- Open Outlook on the web (OWA).
- Navigate to the Office 365 group that you want to change the privacy setting.
- From the group page, click Edit group option as shown in below image.

Convert Office 365 Group as Public or Private Outlook on the web


- Under Privacy, select Public or Private as per your need and click Save to convert the group.

Convert Office 365 Group as Public or Private Outlook on the web