Wednesday, 15 February 2017

Read Multiple Users Profile Properties From SharePoint Online Using CSOM

This post is follow-up of the article http://www.morgantechspace.com/2016/09/read-sharepoint-user-profile-properties-csom.html, in previous post I have clearly explained about how to read current user profile properties, specific user (other user) properties and how to read only required profile properties using client object model (CSOM). One of our user asked the question "How to get a specific profile property (path to profile picture for example) for all of my Sharepoint's website users in one request", so I am writing this post to help every users.

Summary

Get All Profile Properties for Multiple SharePoint Online Users

In the below C# code, I have passed only list of SharePoint Online users, you can fetch all SharePoint Online users using your own best method and use it in below code. You can read users using Azure AD powershell cmdlet Get-MsolUser or you can fetch from your own csv file.
public static void GetMultipleUsersProfileProperties()
{
    string siteUrl = "https://spotenant-admin.sharepoint.com";

    var passWord = new SecureString();
    foreach (char c in "pass@word1".ToCharArray()) passWord.AppendChar(c);
    var credentials = new SharePointOnlineCredentials("admin@spotenant.onmicrosoft.com", passWord);
           
    // Connect to the sharepoint site client context.
    ClientContext clientContext = new ClientContext(siteUrl);
    clientContext.Credentials = credentials;

    // Get the PeopleManager object.
    PeopleManager peopleManager = new PeopleManager(clientContext);

    // Get multiple users
    List<string> Users = new List<string> { "admin@spotenant.onmicrosoft.com",
"alexw@spotenant.onmicrosoft.com", "benw@spotenant.onmicrosoft.com" };

    var results = new Dictionary<string, PersonProperties>();
    foreach (var user in Users)
    {
        string loginName = "i:0#.f|membership|" + user;  //claim format login name
        var personProperties = peopleManager.GetPropertiesFor(loginName);
        clientContext.Load(personProperties, p => p.AccountName, p => p.DisplayName,
                           p => p.UserProfileProperties);
        results.Add(loginName, personProperties);
    }
    clientContext.ExecuteQuery();

    foreach (var kvp in results)
    {
        if (kvp.Value.ServerObjectIsNull.HasValue && !kvp.Value.ServerObjectIsNull.Value)
        {
            Console.WriteLine(kvp.Value.DisplayName);
            Console.WriteLine("---------------------------------");
            foreach (var property in kvp.Value.UserProfileProperties)
            {
                Console.WriteLine(string.Format("{0}: {1}",
                    property.Key.ToString(), property.Value.ToString()));
            }                    
        }
        else
        {
            Console.WriteLine("User not found:"+kvp.Key);
        }
        Console.WriteLine("------------------------------");
        Console.WriteLine("          ");
    }
}

Get Specific Profile Properties for Multiple SharePoint Online Users

The below csom based C# code read only specific set of properties for set of SharePoint Online users.
public static void GetSpecificProfilePropertiesForAllUsers()
{
    string siteUrl = "https://spotenant-admin.sharepoint.com";

    var passWord = new SecureString();
    foreach (char c in "pass@word1".ToCharArray()) passWord.AppendChar(c);
    var credentials = new SharePointOnlineCredentials("admin@spotenant.onmicrosoft.com", passWord);

    // Connect to the sharepoint site client context.
    ClientContext clientContext = new ClientContext(siteUrl);
    clientContext.Credentials = credentials;

    // Get the PeopleManager object.
    PeopleManager peopleManager = new PeopleManager(clientContext);

    // Get multiple users - you can provide all users by fetching with different service
    // Ex: from Get-MsolUser powershell cmdlet
    List<string> Users = new List<string> { "admin@spotenant.onmicrosoft.com",
"alex2w@spotenant.onmicrosoft.com", "benw@spotenant.onmicrosoft.com" };

    var results = new Dictionary<string, IEnumerable<string>>();
    foreach (var user in Users)
    {
        string loginName = "i:0#.f|membership|" + user;  //claim format login name
        // Retrieve specific properties by using the GetUserProfilePropertiesFor method.  
        string[] profilePropertyNames = new string[] { "PersonalSpace", "PictureURL", "SPS-JobTitle" };
        UserProfilePropertiesForUser profilePropertiesForUser = new UserProfilePropertiesForUser(
            clientContext, loginName, profilePropertyNames);

        IEnumerable<string> profilePropertyValues = peopleManager.GetUserProfilePropertiesFor(profilePropertiesForUser);

        // Load the request for the set of properties. 
        clientContext.Load(profilePropertiesForUser);
        results.Add(loginName, profilePropertyValues);
    }
    clientContext.ExecuteQuery();

    foreach (var kvp in results)
    {
        if (kvp.Value != null && kvp.Value.Count() > 0)
        {
            Console.WriteLine("User :" + kvp.Key);
            // Returned collection contains only property values 
            foreach (var value in kvp.Value)
            {
                Console.WriteLine(value);
            }
        }
        else
        {
            Console.WriteLine("User not found:" + kvp.Key);
        }
    }
}

Tuesday, 14 February 2017

Disable AD User based on specific attribute using Powershell

In this article, I am going write powershell script to disable Active Directory user account by using user's specific property like employeeNumber, employeeID, etc...You can disable an ad user account by using the Active Directory powershell cmdlet Disable-ADAccount.
Disable-ADAccount -Identity <adaccount>
The Identity parameter specifies the Active Directory user that you want to disable. You can identify an account by its distinguished name (DN), GUID, security identifier (SID), or samAccountName.

Using the above command, you can not find user by using other AD attributes. So, we need to use another cmdlet Get-ADUser to find user using specific attribute and then we can pipe the result to Disable-ADAccount command to disable.

The following command search an AD user by user's EmployeeID using SQL like filter and disable the user.
Import-Module ActiveDirectory
Get-ADUser -Filter 'employeeID -like "1200547"' | Disable-ADAccount
You can also find an user by using well-known LDAP Filter. The following command find user by LDAP filter using user's EmployeeID and disable the user.
Import-Module ActiveDirectory
Get-ADUser -LDAPFilter '(employeeID=1200547)'  | Disable-ADAccount

Disable Bulk AD Users from CSV by User's EmployeeID

The following powershell script import AD users from csv file and disable by using user's EmployeeID property. Consider the CSV file Users.csv which contains set of AD users to disable with the attribute EmployeeID as one of the csv column header.
Import-Module ActiveDirectory
Import-Csv "C:\Users.csv" | ForEach-Object {
$employeeID = $_."EmployeeID"
Get-ADUser -LDAPFilter "(employeeID=$employeeID)"  | Disable-ADAccount
Write-Host "User $employeeID disabled"
}

Monday, 13 February 2017

Get the list of External users in SharePoint Online using Powershell

We can get the list of all external users in a SharePoint Online tenant using SharePoint Online Powershell cmdlet Get-SPOExternalUser and we can also find and list all the Office 365 guest users by using the Azure AD Powershell cmdlet Get-MsolUser. In this post, I am going to write script to export list of all the external user details to csv file.

Summary:


Get all the External users using Get-SPOExternalUser cmdlet

The below script list the external users from first page. You have to specify your SharePoint Online Admin Center url and Office 365 Admin Credentials to run the following commands.
#Connection to SharePoint Online
$SPOAdminSiteUrl="https://<YourDomain>-admin.sharepoint.com/" 
$365Logon = Get-Credential
Connect-SPOService -Url $SPOAdminSiteUrl -Credential $365Logon  

Get-SPOExternalUser -Position 0 -PageSize 50 | Select DisplayName,Email | FT
If you want to retrieve users from second page, you have to set the position as 1. The below command returns first 10 external users from the second page of the collection.
Get-SPOExternalUser -Position 1 -PageSize 10
You can also specify the parameter SiteUrl to retrieve external users only for a specific site.
Get-SPOExternalUser -Position 0 -PageSize 50 -SiteUrl <YourSiteUrl>

Fetch all the Office 365 External (Guest) users using Get-MsolUser cmdlet

The above command Get-SPOExternalUser will be very helpful if you have minimum number of external users. But it will be difficult if you have 100s of users as you have to fetch users page by page. So to overcome this problem, we can use the Azure AD Powershell cmdlet Get-MsolUser.
#Connection to Azure AD Module
Import-Module MSOnline
$365Logon = Get-Credential
Connect-MsolService –Credential $365Logon

Get-MsolUser -All | ? {$_.UserType -eq "Guest"} | Select DisplayName,SignInName | FT
The above command returns all the Office 365 external users (guest users). You can also apply more where filter to get users from specific domain. The below command returns users only from the domain TestDomain.com.
Get-MsolUser -All | ? {$_.UserType -eq "Guest"} | ? {$_.SignInName -like "*TestDomain.com"}

Export all the External user details to CSV file

You can easily export the external user details to csv file by using the cmdlet Export-Csv.
Get-MsolUser -All | ? {$_.UserType -eq "Guest"} | Select DisplayName,SignInName |
Export-CSV "C:\\External-Users.csv" -NoTypeInformation -Encoding UTF8

Thursday, 9 February 2017

Update Office 365 License features using Powershell

You can easily add a new license with required features and remove an existing license using Azure AD Powershell cmdlet Set-MsolUserLicense. In certain scenario you may need to update an existing license features (enable or disable license sub plans) using this cmdlet.

Use the below command to set a new license.
Set-MsolUserLicense -UserPrincipalName 'morgan@contoso.com' -AddLicenses 'contoso:ENTERPRISEPACK'
To assign multiple licenses, you have to provide AccountSkuId of all the licenses as comma (,) separated values.
Set-MsolUserLicense -UserPrincipalName 'morgan@contoso.com' -AddLicenses contoso:ENTERPRISEPACK,contoso:AAD_PREMIUM
You can enable only particular set of features while adding new license to an user. we have to use the powershell cmdlet New-MsolLicenseOptions to set license features that we want to disable (or remove) from new license.
$options = New-MsolLicenseOptions -AccountSkuId 'contoso:O365_BUSINESS_PREMIUM' -DisabledPlans OFFICE_BUSINESS,MCOSTANDARD
Set-MsolUserLicense -UserPrincipalName 'morgan@contoso.com' -LicenseOptions $options –AddLicenses 'contoso:O365_BUSINESS_PREMIUM'
Note: There is no option EnabledPlans like DisabledPlans, so we can't set only required features in straightforward way, we can achieve this only by excluding non-required features by using DisabledPlans option.

Update existing Office 365 License features

If you want to update or disable license features in existing license, you have to set only LicenseOptions in Set-MsolUserLicense cmdlet (exclude the parameter –AddLicenses).
$options = New-MsolLicenseOptions -AccountSkuId 'contoso:O365_BUSINESS_PREMIUM' -DisabledPlans OFFICE_BUSINESS,MCOSTANDARD
Set-MsolUserLicense -UserPrincipalName 'morgan@contoso.com' -LicenseOptions $options