Monday, 13 June 2016

Retrieve File Version Properties And Version Author Details On SharePoint Using CSOM PowerShell


In this article, you will learn how to retrieve version properties and version author details of files present on SharePoint folders programmatically using CSOM with PowerShell on SharePoint 2013 / SharePoint 2016 / SharePoint online.


Steps Involved:


The following prerequisites need to be executed before going for any operations using CSOM PowerShell on SharePoint sites.
  1. Add the references using the Add-Type command with the necessary reference paths. The necessary references are Microsoft.SharePoint.Client.dll, Microsoft.SharePoint.Client.Runtime.dll.

    Add-Type –

    Path "C:\Program Files\SharePoint Online Management Shell\Microsoft.Online.SharePoint.PowerShell\Microsoft.SharePoint.Client.dll

    Add-Type –

    Path "C:\Program Files\SharePoint Online Management Shell\Microsoft.Online.SharePoint.PowerShell\Microsoft.SharePoint.Client.Runtime.dll
  2. Initialize client context object with the site URL.
    1. $siteURL = ""  
    2. $ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteURL)  
  3. If you are trying to access a SharePoint Online site then you need to set up the site credentials with the credentials parameter and load it to the client context. 
    1. #Not required for on premise site - Start  
    2. $userId = ""  
    3. $pwd = Read-Host -Prompt "Enter password" -AsSecureString  
    4. $creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($userId, $pwd)  
    5. $ctx.credentials = $creds  
    6. #Not required for on premise site - End  
  4. If you are trying to access the SharePoint on premise site then the credentials parameter is not required to be set to the context but you need to run the code on the respective SharePoint Server or you need to pass the network credentials and set the context.
    1. #Credentials for on premise site - Start    
    2. $pwd = Read-Host -Prompt "Enter password" -AsSecureString    
    3. $creds = New-Object System.Net.NetworkCredential("domain\userid", $pwd)    
    4. $ctx.Credentials = $creds    
    5. #Credentials for on premise site - End  


Retrieve File Versions:


  • Initialize the web object using the context and url.
  • Retrieve the folder using the web object and folder title.
  • Create caml query object and assign query xml to get the necessary file from the folder.
  • Get items with GetItems method using the above query.
    1. web = $ctx.Site.OpenWeb("/")  
    2. $folder = $web.Lists.GetByTitle("Documents")  
    3. $query = "<View><Query><Where><Eq><FieldRef Name='Title'/><Value Type='Text'>filename</Value></Eq></Where></Query></View>"  
    4. $camlQuery = New-Object Microsoft.SharePoint.Client.CamlQuery  
    5. $camlQuery.ViewXml = $query  
    6. $items = $folder.GetItems($camlQuery)  
    7. #$items = $folder.GetItems([Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery())  
    8. $ctx.Load($items)  
    9. $ctx.ExecuteQuery()  
  • From the items collections, take the first item and get the necessary details. You can also use foreach loop to see information about multiple files.
  • Access the file, and then file versions. Load the file and version objects, and execute the query.
    1. $item = $items[0]  
    2. $file = $item.File  
    3. $versions = $file.Versions  
    4. $ctx.Load($file)  
    5. $ctx.Load($versions)  
    6. $ctx.ExecuteQuery()  
    7.   
    8. Write-Host $item["Title""Version Details"  
  • Then using foreach loop, get each and every version information. The properties which can be accessed are version label, file URL, created time, version id, current version flag, version file size, version comment, and author details.
  • To get the version author details, load the author object and execute with context to get information about author. The author details which can be accessed are name, email id, and login id.
    1. foreach($version in $versions){  
    2.     $ctx.Load($version)  
    3.     $ctx.ExecuteQuery()  
    4.     Write-Host "--------------------------------------------------------"              
    5.     Write-Host "Version Label      : " $version.VersionLabel              
    6.     Write-Host "Version File URL   : " $version.Url  
    7.     Write-Host "Version Created On : " $version.Created       
    8.       
    9.     Write-Host "Version ID         : " $version.ID  
    10.     Write-Host "Current Version?   : " $version.IsCurrentVersion  
    11.     Write-Host "Version File Size  : " $version.Size  
    12.     Write-Host "Version Comment    : " $version.CheckInComment  
    13.     $modifiedBy = $version.CreatedBy  
    14.     $ctx.Load($modifiedBy)  
    15.     $ctx.ExecuteQuery()  
    16.     Write-Host "File Modified By : "   
    17.     Write-Host $modifiedBy.Title  
    18.     Write-Host $modifiedBy.Email  
    19.     Write-Host $modifiedBy.LoginName  
    20.     Write-Host "--------------------------------------------------------"  
    21. }  

Copy List Items From One SharePoint List To Another Using CSOM PowerShell


In this article, you will learn how to copy list items from one list to another list using CSOM Powershell on SharePoint. This is mainly focused on using PowerShell scripts for any SharePoint 2013 / SharePoint 2016 / SharePoint online sites.


Steps Involved:


The following prerequisites need to be executed before going for any operations using CSOM PowerShell on SharePoint sites.
  1. Add the references using the Add-Type command with the necessary reference paths. The necessary references are Microsoft.SharePoint.Client.dll, Microsoft.SharePoint.Client.Runtime.dll.
    1. Add-Type –Path "C:\Program Files\SharePoint Online Management Shell\Microsoft.Online.SharePoint.PowerShell\Microsoft.SharePoint.Client.dll"  
    2. Add-Type –Path "C:\Program Files\SharePoint Online Management Shell\Microsoft.Online.SharePoint.PowerShell\Microsoft.SharePoint.Client.Runtime.dll"  
  2. Initialize client context object with the site URL.
    1. $siteURL = ""  
    2. $ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteURL)  
  3. If you are trying to access SharePoint Online site then you need to setup the site credentials with credentials parameter and load it to the client context. 
    1. #Not required for on premise site - Start  
    2. $userId = ""  
    3. $pwd = Read-Host -Prompt "Enter password" -AsSecureString  
    4. $creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($userId, $pwd)  
    5. $ctx.credentials = $creds  
    6. #Not required for on premise site - End  
  4. If you are trying to access the SharePoint on premise site then the credentials parameter is not required to be set to the context but you need to run the code on the respective SharePoint Server or you need to pass the network credentials and set the context.
    1. #Credentials for on premise site - Start    
    2. $pwd = Read-Host -Prompt "Enter password" -AsSecureString    
    3. $creds = New-Object System.Net.NetworkCredential("domain\userid", $pwd)    
    4. $ctx.Credentials = $creds    
    5. #Credentials for on premise site - End  


Copy Operation:


We will see how we can copy the list items from one list to another list. Here, the list should have identical SharePoint list fields. The values will be copied only if the corresponding fields are present on both source and destination lists.
  • Using the context, access the web.
  • From the web, get the source list and destination list using the list names.
  • From the source list, get the items using the query object. The query object should be initiated to access the necessary source list items. In this case, I have used All Items query to get all the items.
  • Load and execute the query.
    1. $list1 = $ctx.Web.Lists.GetByTitle("List1")  
    2. $list2 = $ctx.Web.Lists.GetByTitle("List2")  
    3. $list1Items = $list1.GetItems([Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery())  
    4. $fields = $list1.Fields  
    5. $ctx.Load($list1Items)  
    6. $ctx.Load($list1)  
    7. $ctx.Load($list2)  
    8. $ctx.Load($fields)  
    9. $ctx.ExecuteQuery()  
After executing the above steps, we can access the source list, destination list, source list items and source list columns (fields). Now we will see how we can copy items. For each source list item available, execute the below operations.
  • For destination list, create list item creation information object and add the object to the destination list.
  • Access all the fields using for each loop from the source list.
  • For every field, check whether field is not read only field. If it is read only field, then we will not be able to write it to the destination list.
  • Also the fields should not be hidden, attachment or content type, since the write operations will not be possible on these fields.
  • For other custom fields, execute the copy operations and update the item.
    1. foreach($item in $list1Items){  
    2.     Write-Host $item.ID  
    3.     $listItemInfo = New-Object Microsoft.SharePoint.Client.ListItemCreationInformation  
    4.     $list2Item = $list2.AddItem($listItemInfo)  
    5.       
    6.     foreach($field in $fields){  
    7.         #Write-Host $field.InternalName " - " $field.ReadOnlyField   
    8.         if((-Not ($field.ReadOnlyField)) -and (-Not ($field.Hidden)) -and ($field.InternalName -ne  "Attachments") -and ($field.InternalName -ne  "ContentType"))  
    9.         {  
    10.             Write-Host $field.InternalName " - " $item[$field.InternalName]  
    11.             $list2Item[$field.InternalName] = $item[$field.InternalName]  
    12.             $list2Item.update()  
    13.         }  
    14.     }  
    15. }  
    16. $ctx.ExecuteQuery()  

Tuesday, 31 May 2016

Working With SharePoint Web Scoped Site Features Using REST API


In this article, you will learn how to retrieve, enable or disable the site features (Web Scoped features) programmatically using REST API on SharePoint 2013 / SharePoint 2016 / SharePoint online. Here, we will see in detail about the usage of REST API to complete these operations. The web scoped features are present on this page.


Steps Involved:


  • Identify the site or sub site URL and build the REST API URL.
  • URL is built in the below sections, web denotes the sites or sub sites and sets the necessary parameters to filter out the data. You need to provide select parameters to get the necessary feature properties in get request.
  • Use Ajax jQuery call to accomplish the necessary operation.
  • You can set the return value type in the Ajax call request. In my case, I have specified JSON to be the return value in the data parameter.
  • In these cases, you can check the result values in a browser debugger console. You can change the logic to display results on pages.
  • Place these scripts on the page using the web parts (content editor / script editor / any custom web part).


Get Active Site Features and Properties (Web scope):


The operation will fetch all the active site features (web scoped) present on the site or sub site.
  • In the URL, select parameters has necessary properties to be retrieved.
  • Using <for> each loop, get and display the results.
    1. // Retrieves all the site features enabled (web scoped features)  
    2. function GetSiteFeatures(){  
    3.     //  Here site URL can be root level or sub sites. But the web scoped features will be retrieved  
    4.     var featuresURI = siteURL + "/_api/web/features?$select=DisplayName,DefinitionId";  
    5.     $.ajax({  
    6.         url: featuresURI,  
    7.         method: 'GET',  
    8.         headers: { "Accept""application/json; odata=verbose" },  
    9.         dataType: "json",  
    10.         success: function (data) {  
    11.             var siteFeatures = data.d.results;  
    12.             for(var i=0;i<siteFeatures.length;i++){  
    13.                 console.log(siteFeatures[i].DefinitionId + " - " + siteFeatures[i].DisplayName);  
    14.             }  
    15.         },  
    16.         error: function(data) {  
    17.         }  
    18.     });  
    19. }  



Get/Check Site Feature Properties/Status (Web scope):


Here, we will see how we can get the particular feature and check whether the site feature (Web Scoped) is active or not. You can identify whether the feature is activated at Web Scope or not.
  • Get the feature ID from Microsoft site. The scope of the feature should be Web.
  • Get the feature using GetById method with feature ID in the REST API.
    1. // Retrieves all the site features enabled (web scoped features)  
    2. function GetSiteFeatureByID(){  
    3.     var featuresURI = siteURL + "/_api/web/features/GetByID('d95c97f3-e528-4da2-ae9f-32b3535fbb59')?$select=DisplayName,DefinitionId";  
    4.     $.ajax({  
    5.         url: featuresURI,  
    6.         method: 'GET',  
    7.         headers: { "Accept""application/json; odata=verbose" },  
    8.         dataType: "json",  
    9.         success: function (data) {  
    10.             if(data.d.DefinitionId != null){  
    11.                 console.log(data.d.DefinitionId + " - " + data.d.DisplayName + " feature is active");  
    12.             }  
    13.             else{  
    14.                 console.log("Site Feature is not active");  
    15.             }  
    16.         },  
    17.         error: function(data) {  
    18.         }  
    19.     });  
    20. }  



Activate the site feature (Web scope):


In the above section, we saw how we can check the status of the site feature (Web Scoped). Here, we will see how we can activate the feature which is already installed on the site.
  • To activate the site feature, use the ADD method to the features collection. The necessary parameter to be passed in the query is feature ID.
  • POST method will be used to accomplish the task.
  • RequestDigest will be passed in the header to validate the page requests.
    1. // Enables site feature (web scoped feature)  
    2. function EnableSiteFeature(){  
    3.     var featuresURI = siteURL + "/_api/web/features/add('d95c97f3-e528-4da2-ae9f-32b3535fbb59')"// Mobile Browser View Feature ID  
    4.     $.ajax({  
    5.         url: featuresURI,  
    6.         method: 'POST',  
    7.         headers: {   
    8.             "Accept""application/json;odata=verbose",  
    9.             "X-RequestDigest": $("#__REQUESTDIGEST").val()   
    10.         },  
    11.         success: function (data) {  
    12.             console.log("Feature Activated");  
    13.         },  
    14.         error: function(data) {  
    15.             console.log(data.responseJSON.error.message.value);  
    16.         }  
    17.     });  
    18. }  



Deactivate the site feature (Web scope):


In the above section, we have seen how we can activate the site feature (Web Scoped). Here, we will see how we can deactivate the feature.
  • To deactivate the site feature, use the Remove method on URL. The necessary parameters will be passed in the query is feature ID.
  • POST method will be used to accomplish the task.
  • RequestDigest will be passed in the header to validate the page requests.
    1. // Disables site feature (web scoped feature)  
    2. function DisableSiteFeature(){  
    3.     var featuresURI = siteURL + "/_api/web/features/remove('d95c97f3-e528-4da2-ae9f-32b3535fbb59')"// Mobile Browser View Feature ID  
    4.     $.ajax({  
    5.         url: featuresURI,  
    6.         method: 'POST',  
    7.         headers: {   
    8.             "Accept""application/json;odata=verbose",  
    9.             "X-RequestDigest": $("#__REQUESTDIGEST").val()   
    10.         },  
    11.         success: function (data) {  
    12.             console.log("Site Feature De-Activated");  
    13.         },  
    14.         error: function(data) {  
    15.             console.log(data.responseJSON.error.message.value);  
    16.         }  
    17.     });  
    18. }  
Note - The above set of operations needs to be called in order to execute it.
  1. $(document).ready(function(){  
  2.     GetSiteFeatures(); // Retrieves all the site features enabled (web scoped features)  
  3.     GetSiteFeatureByID(); // Retrieves all the site features enabled (web scoped features)  
  4.     EnableSiteFeature(); // Enables site feature (web scoped feature)  
  5.     DisableSiteFeature(); // Disables site feature (web scoped feature)  
  6. });