Tag Archives: Binary Cmdlet

Tip: Create New List in SharePoint Online Using Exception Handling Scope and Set Properties | PowerShell | CSOM

Summary

While presenting about SharePoint Online Client Side Object Model a question popped up “Hey! How can I create a new list if it’s not exist and change properties if exists?”. Not a difficult one. However, we need to build codes with best practise suggested by Microsoft. In short answer is available here.

Requirement

  • Create a List if it’s not existing.
  • Change Properties if it exists.
  • Allow to create multiple lists in one run
  • Allow users to choose the list template.

Solution

Build a binary cmdlet using C# and meet your needs by parameterizing the code. Look at the code below.

using System;
using System.Management.Automation;
using Microsoft.SharePoint.Client;
namespace xSharePointOnline
{
    [Cmdlet(VerbsCommon.New, "SPOList")]
    public class NewSPOList : PSCmdlet
    {
        [Parameter(Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)]
        public Uri SPOurl;
 
        [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)]
        public string SPOListName;
 
        [Parameter(Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)]
        public ListTemplateType SPOListTemplateType;
 
        [Parameter(Mandatory = true)]
        [Credential]
        public PSCredential SPOCredential;
 
        protected override void ProcessRecord()
        {
            base.ProcessRecord();
            using (ClientContext SPOClientContext = new ClientContext(SPOurl))
            {
                SPOClientContext.Credentials = new SharePointOnlineCredentials(SPOCredential.UserName, SPOCredential.Password);
                ExceptionHandlingScope Scope = new ExceptionHandlingScope(SPOClientContext);
                using (Scope.StartScope())
                {
                    using (Scope.StartTry())
                    {
                        List oList = SPOClientContext.Web.Lists.GetByTitle(SPOListName);
                        oList.Update();
                    }
                    using (Scope.StartCatch())
                    {
                        ListCreationInformation oListInformation = new ListCreationInformation();
                        oListInformation.Title = SPOListName;
                        oListInformation.TemplateType = (int)SPOListTemplateType;
                        List oList = SPOClientContext.Web.Lists.Add(oListInformation);
                    }
                    using (Scope.StartFinally())
                    {
                        List oList = SPOClientContext.Web.Lists.GetByTitle(SPOListName);
                        oList.Hidden = true;
                        oList.Description = "PowerShell Rocks!";
                    }
                }
                SPOClientContext.ExecuteQuery();
            }
        }
    }
}

How to use it?

  • Create a C# Class Library
  • Copy and paste the code. If required change the parameters as required.
  • Build it to get the DLL (Binary)
  • Using Import-Module load the binary DLL E.G. Import-Module C:\Location\Solution.DLL
  • Run the cmdlet New-SPOList -SPOUrl -SPOListName -SPOListTemplateType -SPOCredential

Here the SPOListTemplate populate the enum values of List Template – So, we can choose the one we need by tab completion

How it works?

We have used Exception handling scope which makes one call to the server and that means a lot of performance improvement. All three Try, catch and finally executes at one time.
Try
This code simply checks the existence of the list and if exists it will update the hidden and description properties.
Catch
If try catch throws exception it will create a new list – If in case of the list not existing.
Finally
Update the lists properties.

Screen Shot

2746.123

SharePoint Online PowerShell Tip: Conditional Scope – Binary Module

SharePoint Online PowerShell Tip to throw exception while connecting to Tenant.

Introduction

Recently one of our customer requested us to share a code which should throw an exception while connecting to SharePoint Online if in case of credential invalid or not connecting to tenant site. Well, they have a binary module delivered by some suppliers which is pretty straight forward and simple. If all set to good code will execute if not exception thrown in other cmdlet. The module they use has bunch of cmdlets which are more or less mock up of SharePoint Online cmdlets. Connect-SPOService throws exception if credential are invalid and they need custom error message for the custom built cmdlet Connect-SPOTenant

Requirement

  • Connect-SPOTenant : The sign-in name or password does not match one in the Microsoft account system
  • Connect-SPOTenant : Current site is not a tenant administration site.

PowerShell Code

Below is the PowerShell code shared by our client.

function global:Connect-SPOSite {
 [CmdletBinding()]
 param (
 [Parameter(Mandatory=$true, ValueFromPipeline=$true, Position=0)]
 $Url
 )
 
 begin {
 [System.Reflection.Assembly]::LoadFile("C:\Program Files\SharePoint Online Management Shell\Microsoft.Online.SharePoint.PowerShell\Microsoft.SharePoint.Client.dll") | Out-Null
 [System.Reflection.Assembly]::LoadFile("C:\Program Files\SharePoint Online Management Shell\Microsoft.Online.SharePoint.PowerShell\Microsoft.SharePoint.Client.Runtime.dll") | Out-Null
 }
 process {
 if ($global:spoCred -eq $null) {
 $cred = Get-Credential -Message "Enter your credentials for SharePoint Online:"
 $global:spoCred = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($cred.UserName, $cred.Password)
 }
 $ctx = New-Object Microsoft.SharePoint.Client.ClientContext $Url
 $ctx.Credentials = $spoCred
 
 if (!$ctx.ServerObjectIsNull.Value) {
 Write-Host "Connected to site: '$Url'" -ForegroundColor Green
 }
 return $ctx
 }
 end {
 }
}

Solution

Indeed, the above code will not throw any exception because the ClientContext Object is instantiated and will not validate the credential but returns the ClientContext Object as output. More over Microsoft.SharePoint.Client.ClientContext doesn’t have ServerObjectIsNull property. No matter we supply wrong password the host shows Connected to Site!

Conditional Scope

C# code with conditional scope is below. This is just a demo so we haven’t used any scope methods or properties

using System;
using System.Management.Automation;
using Microsoft.SharePoint.Client;
using Microsoft.Online.SharePoint.TenantAdministration;
namespace xSharePointOnline
{
 [Cmdlet(VerbsCommunications.Connect, "SPOTenant")]
 
 public class ConnectSPOTenant : PSCmdlet
 {
 [Parameter()]
 public Uri SPOUrl;
 
 [Parameter()]
 [Credential]
 public PSCredential SPOCredential;
 protected override void ProcessRecord()
 {
 using (ClientContext SPOClientContext = new ClientContext(SPOUrl))
 {
 SPOClientContext.Credentials = new SharePointOnlineCredentials(SPOCredential.UserName, SPOCredential.Password);
 Tenant oTenant = new Tenant(SPOClientContext);
 ConditionalScope Scope = new ConditionalScope(SPOClientContext, () => oTenant.ServerObjectIsNull.Value != true);
 SPOClientContext.ExecuteQuery();
 }
 }
 }
}

Screen Shot

1

2