Friday, 22 September 2017

Block and Unblock access to Office 365 users using PowerShell

Blocking access to an Office 365 account prevents anyone from using the account to sign in and access all the services and data in your Office 365 tenant. We can use the Azure AD powershell cmdlet Set-MsolUser to block user from login into Office 365 service (Ex: Mailbox, Planner, SharePoint, etc).

Block and Unblock an Office user account:

We need to set the user associated property BlockCredential to block user access to Office 365 service.
Set-MsolUser -UserPrincipalName -BlockCredential $true
The following command unblock the blocked user.
Set-MsolUser -UserPrincipalName -BlockCredential $false

Block multiple Office 365 user accounts:

We can use the command Get-MsolUser to fetch set of required Azure AD users with proper filter and then pipe the results to Set-MsolUser cmdlet to block access to every user.
Get-MsolUser -All | Where {$_.Department -eq "Testing"} |
Set-MsolUser -BlockCredential $true

Block bulk user accounts by import CSV file:

We may required to block access to bulk of user accounts, in this case we can have user ids in csv. We need to import csv file, and then pass every user to Set-MsolUser cmdlet. Consider the csv file Block_Users.csv that has users with the column header UserPrincipalName.
Import-Csv 'C:\Block_Users.csv' | ForEach-Object {
$upn = $_."UserPrincipalName"
Set-MsolUser -UserPrincipalName $upn -BlockCredential $true

Export blocked user accounts to CSV file:

Run the following command to export all the users that have been blocked to access Office 365 services.
Get-MsolUser -All | Where {$_.BlockCredential -eq $True} |
Select DisplayName,UserPrincipalName, BlockCredential |
Export-CSV "C:\\Blocked_Users.csv" -NoTypeInformation -Encoding UTF8


No comments:

Post a Comment