In this article, you will learn how to retrieve or add users as site collection administrators from/to SharePoint online sites, using PnP Core CSOM library.
The main advantage of using PnP Core libraries is the reduced code to get the required information. The required object can be retrieved with a very small piece of code, once the client context is set.
PnP Core CSOM documentation can be found on the official site here.
PnP Core CSOM library packages can be downloaded here.
The code, given below, is being tested, using Visual Studio console Application. Once the console application is created, the packages can be installed, using "Install-Package SharePointPnPCoreOnline" command on Package Manager console of Visual Studio. Once installed, the references and packages will be imported to the solution.
The references used in the sample are given below.
Connect to SharePoint Online site
The Authentication Manager is used to retrieve the client context of the site. To connect to SharePoint Online site, the token, given below is used.
The parameters required are.
SharePoint Online site URL
Tenant Password (or secured string)
Add Site Collection Admins
Users can be added as site collection admins to SharePoint online sites, using PnP Core component. The following steps explain the process in detail.
Input the site detail, user details for authentication, and site collection admin information.
Authenticate and get the client context of the site and then the necessary Web object.
Using Web object, add the users using AddAdministrators method. The required parameters are given below.