Tag Archives: CSOM

Delete Navigation (Top Navigation or Quick Launch Node) Using CSOM and PowerShell

1

A colleague asked me a script for deleting nodes from Global Navigation or from Quick Launch in a SharePoint Site. Before we get into the PowerShell script lets know about the Navigation (In General). The below image illustrates the navigation settings in a SharePoint Site

2

All the headings with folder signs are parent nodes and links are children i.e child nodes. The requirement for now is to remove the parent node which can be accomplished by enumerating the appropriate collections QuickLaunch and TopNavigationBar. Here is the full script

Import-Module C:\Scripts\CSOMOnlineAssemblies\Microsoft.SharePoint.Client.dll
Import-Module C:\Scripts\CSOMOnlineAssemblies\Microsoft.SharePoint.Client.Runtime.dll

function Remove-xSPONavigationNode 
{
<#
.Synopsis
   PowerShell script to delete the parent node from Quick Launch or from Global Navigation
.DESCRIPTION
   This PowerShell script is to delete the parent node including the child nodes from Quick Launch i.e (Current Navigation)
   or from Global Navigation (Top Level Navigation bar) 
.EXAMPLE
   Remove-xSPONavigationNode -Url https://contoso.sharepoint.com -Title 'Tasks' -NavigationType QuickLaunch -Credential 'admin@contoso.onmicrosoft.com'
   Delete the node name Tasks and child nodes from the given site (Quick Launch)
.EXAMPLE
   Remove-xSPONavigationNode -Url https://contoso.sharepoint.com -Title 'Subsite' -NavigationType GlobalNavigation -Credential 'admin@contoso.onmicrosoft.com'
   Delete the node name Subsite and child nodes from the given site (Global Navigation)
.LINK 
   
Delete Navigation (Top Navigation or Quick Launch Node) Using CSOM and PowerShell
.NOTE @ChendrayanV http://chen.about-powershell.com #> param ( [Parameter(Mandatory,ValueFromPipeline,ValueFromPipelineByPropertyName)] $Url, [Parameter(Mandatory,ValueFromPipeline,ValueFromPipelineByPropertyName)] $Title, [Parameter(Mandatory)] [ValidateSet('QuickLaunch' ,'GlobalNavigation')] $NavigationType, [Parameter(Mandatory)] [System.Management.Automation.CredentialAttribute()] [pscredential] $Credential ) process { try { $SPOClientContext = [Microsoft.SharePoint.Client.ClientContext]::new($Url) $SPOClientContext.Credentials = [Microsoft.SharePoint.Client.SharePointOnlineCredentials]::new($Credential.UserName,$Credential.Password) switch ($NavigationType) { "QuickLaunch" { $QuickLaunchNodes = $SPOClientContext.Web.Navigation.QuickLaunch $SPOClientContext.Load($QuickLaunchNodes) $SPOClientContext.ExecuteQuery() $SPOClientContext.Dispose() for($i=$QuickLaunchNodes.Count-1;$i -ge 0; $i--) { if($QuickLaunchNodes[$i].Title -eq $Title) { $QuickLaunchNodes[$i].DeleteObject() } } $SPOClientContext.ExecuteQuery() $SPOClientContext.Dispose() } "GlobalNavigation" { $GlobalNavigationNodes = $SPOClientContext.Web.Navigation.TopNavigationBar $SPOClientContext.Load($GlobalNavigationNodes) $SPOClientContext.ExecuteQuery() $SPOClientContext.Dispose() for($i=$GlobalNavigationNodes.Count-1;$i -ge 0; $i--) { if($GlobalNavigationNodes[$i].Title -eq $Title) { $GlobalNavigationNodes[$i].DeleteObject() } } $SPOClientContext.ExecuteQuery() $SPOClientContext.Dispose() } } } catch { $_.Exception.Message } } }

How to use this script? Copy paste the code in your script location for example C:\Scripts and follow the below steps. Warning: If you have deleted the node it can’t be restored.

PS C:\Scripts> . .\Remove-xSPONavigationNode.ps1

Remove-xSPONavigationNode -Url https://contoso.sharepoint.com -Title 'Subsite' -NavigationType GlobalNavigation -Credential $Credential

Remove-xSPONavigationNode -Url https://contoso.sharepoint.com -Title 'Tasks' -NavigationType QuickLaunch -Credential $Credential

'Subsite2' , 'Subsite3' | Remove-xSPONavigationNode -Url https://contoso.sharepoint.com -NavigationType GlobalNavigation -Credential $Credential

$Credential = Get-Credential -Credential ‘admin@contoso.onmicrosoft.com’ – By doing this we can pass multiple site and node title and remove the nodes from different sites

'Subsite2' , 'Subsite3' | Remove-xSPONavigationNode -Url https://contoso.sharepoint.com -NavigationType GlobalNavigation -Credential $Credential

I have removed few nodes from Top and Quick and the below image illustrates it. (Compare the preceding image)

4

In my next blog I will share few more scripts for SharePoint Online which may helps content managers to manage the site easily. Enjoy PowerShell!

Retrieve SharePoint Site Groups Information Using PowerShell

A colleague asked me a script to retrieve SharePoint Site Groups information by excluding the user’s information and added he couldn’t use Select-Object cmdlet to exclude user’s collection in the group property. Yes, it’s not possible! But, we have a fix for it and here is the PowerShell script to get Group properties by ignoring the UserCollection property in it

Import-Module C:\Users\904870.CORPORATEROOT\Documents\WindowsPowerShell\Modules\xMicrosoft.SharePointOnline.PowerShell\Microsoft.SharePoint.Client.dll
$UserName = "chendrayan@contoso.com"
$Credential = ConvertTo-SecureString -String "P@ssw0rd" -AsPlainText -Force
$ctx = [Microsoft.SharePoint.Client.ClientContext]::new("https://contoso.sharepoint.com")
$ctx.Credentials = [Microsoft.SharePoint.Client.SharePointOnlineCredentials]::new($UserName,$Credential)
$Groups = $ctx.Web.SiteGroups
$ctx.Load($Groups)
$ctx.ExecuteQuery()
$ctx.Dispose()
$Props = ([Microsoft.SharePoint.Client.Group].GetProperties() | ? {$_.PropertyType -notlike '*Collection*'}).Name 
foreach($Group in $Groups)
{
    [Microsoft.SharePoint.Client.Group]$Group | Select -Property $Props
}

Reason: We need to explicit request and execute to get user collection information but in our case it’s not required. So, simply we skipped the property which has type as collection. Note: In group property user is the only collection type property.

Part 4 – Getting Started With CSOM | SharePoint Online | PowerShell

Introduction

We discussed and show cased few PowerShell and CSOM functionalities in earlier blogs. Please refer to the links below

In Part 3 we showed the steps to add Format files for our Script module and in this article we will demo an alternate method to Add custom view for our objects without creating PSOject explicitly and this is just a tip to get List Property information. Do remember we are using CSOM and PowerShell and there are high chances of performance issues which will be addressed in later upcoming blog articles. For, now we will cover alternate options.

Code at Ease

process {
        $SPOClientContext = [Microsoft.SharePoint.Client.ClientContext]::new($Url)
        $SPOClientContext.Credentials = $Credential
        $ListCollection = $SPOClientContext.Web.Lists
        $SPOClientContext.Load($ListCollection)
        $SPOClientContext.ExecuteQuery()
        $SPOClientContext.Dispose()
        foreach($List in $ListCollection) {
            $List.PSOBject.TypeNames.Insert("0" , "SharePointOnline.Format.Custom.ListView")
            $List
        }
    }

What we did here is a very simple and ugly way of getting List Information and created a default view using Format.ps1xml. The advantage is we will allow users to select the required properties! So, no need to type all properties names and keeps the code neat and clean. Again! Please ignore the performance we will discuss about it soon. This function takes maximum 4 seconds and 1 second minimum to query.

Output

333 Well! It looks good for now! Let’ test it with different properties

Get-xSPOList -Url https://chensoffice365.sharepoint.com  | Select -First 5 | Select Title , NoCrawl

Get-xSPOList -Url https://chensoffice365.sharepoint.com  | Select -First 5 | Select Title , NoCrawl , Hidden

Result

444

Part 1 – Getting Started With CSOM | SharePoint Online | PowerShell

Introduction

CSOM is no more a secret for SharePoint IT Professionals and developers. MS released a new version of SharePoint Online CSOM and it’s available in Nuget which makes our life bit easier. All we need is to run Install-Package “Microsoft.SharePointOnline.CSOM” -Verbose 2016-05-24_14-32-44 We can use VS Community Edition for building binary modules or use Visual Studio Code editor to build scripts or script modules. After installing the packages I found my Nuget folder under the path “C:\Program Files\NuGet\” and the required DLL are located in “C:\Programfiles\NuGet\Packages\Microsoft.SharePointOnline.CSOM.16.1.5026.1200\lib\net45“. The DLL files are listed below. This is a part 1 so we will just use Two DLL’s for now to get very basic information.

  • Microsoft.Office.Client.Policy.dll
  • Microsoft.Office.Client.TranslationServices.dll
  • Microsoft.Office.SharePoint.Tools.dll
  • Microsoft.Online.SharePoint.Client.Tenant.dll
  • Microsoft.ProjectServer.Client.dll
  • Microsoft.SharePoint.Client.dll
  • Microsoft.SharePoint.Client.DocumentManagement.dll
  • Microsoft.SharePoint.Client.Publishing.dll
  • Microsoft.SharePoint.Client.Runtime.dll
  • Microsoft.SharePoint.Client.Runtime.Windows.dll
  • Microsoft.SharePoint.Client.Search.Applications.dll
  • Microsoft.SharePoint.Client.Search.dll
  • Microsoft.SharePoint.Client.Taxonomy.dll
  • Microsoft.SharePoint.Client.UserProfiles.dll
  • Microsoft.SharePoint.Client.WorkflowServices.dll

Using Import-Module “Path to DLL” I loaded the binaries to my PowerShell session so the Visual Studio Code will help us in intellisense. Thus, we do code at ease! The below function will establish the connection to SharePoint Online at tenant level. To understand the SharePoint Online site hierarchy refer the below image (Just as a References)a30d1b67-e6ff-4fea-bc44-5f00ba7fcc33 PowerShell Code to Connect With SharePoint Online Tenant

function Connect-xSPOTenant {
    [CmdletBinding()]
    param(
        [uri]
        $Url,
        
        [System.Management.Automation.CredentialAttribute()]
        $Credential
    )
    
    begin {
    }
    
    process {
        if($Script:Credential -eq $null) {
            $Credentials = Get-Credential -Message "SharePoint Online Credential" 
            $Script:Credential = [Microsoft.SharePoint.Client.SharePointOnlineCredentials]::new($Credentials.UserName , $Credentials.Password)
            $SPOClientContext = [Microsoft.SharePoint.Client.ClientContext]::new($Url);
            $SPOClientContext.Credentials = $Credential;
        }
        
    }
    
    end {
    }
}

Just halt here! We didn’t use the conditional scopes to validate. If you pass incorrect values to variables no exception will be thrown. If you are planning to commit this in Binary module then refer this blog post. After establishing the connection we can query different site collections to get list information. For example, refer the following function which connects to one of the Site Collections and retrieve List Information.

function Get-xSPOList {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory,ValueFromPipeline,ValueFromPipelineByPropertyName)]
        [uri]
        $Url
    )
    
    begin {
    }
    
    process {
        $SPOClientContext = [Microsoft.SharePoint.Client.ClientContext]::new($Url)
        $SPOClientContext.Credentials = $Credential
        $ListCollection = $SPOClientContext.Web.Lists
        $SPOClientContext.Load($ListCollection)
        $SPOClientContext.ExecuteQuery()
        $SPOClientContext.Dispose()
        foreach($List in $ListCollection) {
            $List | Select Title , ItemCount
        }
    }
    
    end {
    }
}

The below figure illustrates the output.
2016-05-24_15-39-18 In our next blog we will add some more functions and show case creating modules.

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

Bulk Import Folders and Files in SharePoint Document Library | Part 1

This noon I was on a call with SharePoint Development team to discuss few activities which is pretty straight forward approach for SharePoint IT Professionals. However, we need to inform about the activity we carry out in the farm to both IT Pro’s and developers. By doing this we simply avoid confusion. And, as always in any farm bulk upload of files and folders may cause one or other issues like threshold, performance high risk of uploading vulnerable files etc.

Our client came with 5000 odd folders which has almost 9000 files approximately and the requirement is to push it to document folder. For example, files underneath the folder should be organized as a single folder and files needs to be stored in it. The appended a request “Share the cmdlet so we can add more in future!”

Everything is easy if we build one! There is no out of the box solution. We can’t drag and drop easily as we know the limitations in document library. So, I built a small cmdlet in Visual C# which serves the purpose.

The folder structure is very simple, Main Folder which contains N number of folder and each folder may have some files. No Folders underneath the folders.

using System;
using System.IO;
using System.Management.Automation;
using Microsoft.SharePoint.Client;
namespace SP2010Admin
{
    [Cmdlet(VerbsData.Import, "Document")]
    public class ImportDocument : Cmdlet
    {
        [Parameter(Mandatory = true)]
        public Uri SPUrl;
        [Parameter(Mandatory = true)]
        public string SPDocLib;
        [Parameter(Mandatory = true,
                   ValueFromPipeline = true,
                   ValueFromPipelineByPropertyName = true)]
        public string FolderPath;
        protected override void ProcessRecord()
        {
            ClientContext ctx = new ClientContext(SPUrl);
            Web web = ctx.Web;
            ctx.Load(web);
            ctx.ExecuteQuery();

            List DocLib = web.Lists.GetByTitle(SPDocLib);
            string[] filenames = Directory.GetFiles(FolderPath);
            DirectoryInfo dInfo = new DirectoryInfo(FolderPath);
            FolderCollection folders = DocLib.RootFolder.Folders;
            ctx.Load(folders);
            ctx.ExecuteQuery();
            bool exists = false;
            foreach (Folder efolder in folders)
            {
                if (efolder.Name.Equals(dInfo.Name))
                {
                    foreach (string filename in filenames)
                    {
                        string[] names = filename.Split('\\');
                        WriteObject("Existing " + filename);
                        byte[] data = System.IO.File.ReadAllBytes(filename);
                        FileCreationInformation fci = new FileCreationInformation();
                        fci.Content = data;
                        fci.Url = names[names.Length - 1];
                        efolder.Files.Add(fci);
                        exists = true;
                    }
                }
            }
            if (!exists)
            {
                Folder tFolder = folders.Add(dInfo.Name);
                foreach (string filename in filenames)
                {
                    string[] names = filename.Split('\\');
                    WriteObject("Uploading file " + filename);
                    byte[] data = System.IO.File.ReadAllBytes(filename);
                    FileCreationInformation fci = new FileCreationInformation();
                    fci.Content = data;
                    fci.Url = names[names.Length - 1];
                    tFolder.Files.Add(fci);
                    exists = true;
                }
                ctx.ExecuteQuery();
            }
        }
    }
}

Usage:

Import-Module "c:\users\ChenV\documents\visual studio 2015\Projects\SP2010Admin\SP2010Admin\bin\Debug\SP2010Admin.dll" -Verbose
(Get-ChildItem "C:\Users\ChenV\ProjectFolder\Test\" -Recurse).FullName | Import-Document -SPUrl http://www.contoso.com/web -SPDocLib "Doc Lib" -Verbose

In Part 2 we will discuss about the best practice and will enhance this code much better! Enjoy PowerShell 🙂 🙂 🙂

Thanks to Author Rashu, Rahul in TechNet Wiki

Get-SPOAppInfo | SharePoint Online | PowerShell

During SharePoint Online discussion a question popped up “How to get all installed application information in SharePoint Online?” a simple answer is Get-SPOAppInfo cmdlet! But, wait we are partially correct but read this documentation https://technet.microsoft.com/en-us/library/fp161398.aspx. The below image illustrates the parameters of Get-SPOAppInfo both set to be false and it’s not $TRUE – This cmdlet needs either Name or Product ID! So, we can’t use this cmdlet to retrieve all the apps installed in the given Tenant!

Issue:

So we can Get installed apps information by using below

Enough! We are not going to use this. Let’s use Client Side Object Model in PowerShell and solve the issue.

Output

Code:

Import-Module C:\SPPowerKit\Microsoft.SharePoint.Client.dll
Import-Module C:\SPPowerKit\Microsoft.SharePoint.Client.Runtime.dll
#Import-Module C:\SPPowerKit\Microsoft.SharePoint.Client.UserProfiles.dll
Import-Module C:\SPPowerKit\Microsoft.Online.SharePoint.Client.Tenant.dll
function Get-SPOAppInformation
{
    param(
    [Parameter(Mandatory=$true)]
    [string]$SPOUrl,

    [Parameter(Mandatory=$true)]
    [System.Management.Automation.CredentialAttribute()]$SPOCredential
    )

    $ClientContext = [Microsoft.SharePoint.Client.ClientContext]::new($SPOUrl)
    $ClientContext.Credentials = [Microsoft.SharePoint.Client.SharePointOnlineCredentials]::new($SPOCredential.UserName,$SPOCredential.Password)
    $Tenant = New-Object Microsoft.Online.SharePoint.TenantAdministration.Tenant -ArgumentList $ClientContext
    $Tenant.Context.Load($Tenant)
    $Tenant.Context.ExecuteQuery()
    $Appinfo = $Tenant.GetAppInfoByName([string]::Empty)
    $Tenant.Context.Load($Appinfo)
    $Tenant.Context.ExecuteQuery()
    $Appinfo
    $ClientContext.Dispose()
}

Get-SPOAppInformation -SPOUrl "https://contoso-admin.sharepoint.com" -SPOCredential "TenantAdmin@contoso.onmicrosoft.com"

Bit more to organize it, we can use PSObject!

Import-Module C:\SPPowerKit\Microsoft.SharePoint.Client.dll
Import-Module C:\SPPowerKit\Microsoft.SharePoint.Client.Runtime.dll
#Import-Module C:\SPPowerKit\Microsoft.SharePoint.Client.UserProfiles.dll
Import-Module C:\SPPowerKit\Microsoft.Online.SharePoint.Client.Tenant.dll
function Get-SPOAppInformation
{
    param(
    [Parameter(Mandatory=$true)]
    [string]$SPOUrl,

    [Parameter(Mandatory=$true)]
    [System.Management.Automation.CredentialAttribute()]$SPOCredential
    )

    $ClientContext = [Microsoft.SharePoint.Client.ClientContext]::new($SPOUrl)
    $ClientContext.Credentials = [Microsoft.SharePoint.Client.SharePointOnlineCredentials]::new($SPOCredential.UserName,$SPOCredential.Password)
    $Tenant = New-Object Microsoft.Online.SharePoint.TenantAdministration.Tenant -ArgumentList $ClientContext
    $Tenant.Context.Load($Tenant)
    $Tenant.Context.ExecuteQuery()
    $Appinfocollection = $Tenant.GetAppInfoByName([string]::Empty)
    $Tenant.Context.Load($Appinfocollection)
    $Tenant.Context.ExecuteQuery()
    foreach($Apps in $Appinfocollection)
    {
        $Results = New-Object psobject -Property ([Ordered]@{
        Name = $Apps.Name
        ProductID = $Apps.ProductID
        Source = $Apps.Source
        })
        $Results
    }
    $ClientContext.Dispose()
}

Get-SPOAppInformation -SPOUrl "https://contoso-admin.sharepoint.com" -SPOCredential "TenantAdmin@contoso.onmicrosoft.com"

2016-01-20_10-22-29

Converting JSON Time Format in SharePoint Document Library Metadata


The SharePoint farm has a Document Library and a List which are linked for some requirements, while querying information we received some data which are not in proper format. Challenge is to split, remove characters and count the total which is little tedious

Example- The Field3 in CSV yields [“\/Date(1444995273796)\/”,”\/Date(1444996968515)\/”]

It’s a JSON format and the time format is EPOCH (UNIX format) – With Reference to the link MSDN My advice to customer was to use below code snippet to break the mystery!

To get the count: (Unfortunately, this is what customer need!) – No Fun in it because this kills the actual flavor of SharePoint development and data.

(@"
["\/Date(1444995273796)\/","\/Date(1444996968515)\/"]
"@ | ConvertFrom-Json).Count

#Output
#2

The reason for the SPContext Code by developer is unknown. So here comes the ConvertFrom-JSON power in Windows PowerShell Version 3+ 🙂 🙂 🙂

To get the information about the data in JSON: [We will deep dive in Part 2 of this Blog]

@"
["\/Date(1444995273796)\/","\/Date(1444996968515)\/"]
"@ | ConvertFrom-Json

#Output

#Friday, October 16, 2015 11:34:33 AM
#Friday, October 16, 2015 12:02:48 PM

The file which is generated as report is done using C# and CSOM – So, in next blog post (Part 2) we will cover Binary Module using C# Class Library, PowerShell Module, String Manipulation and Data consolidation.

Enjoy PowerShell !

Show or Hide SharePoint List Using CSOM | C# | PowerShell

Disclaimer: This is pretty old topic just remade it using CSOM and PowerShell at my client work place.

During SharePoint due diligence many suggested to use SharePoint Manager Tools, CAML Query Builder etc. It’s better to keep tools handy but gathering and executing the client requirement is better than the best.

Environment: Client has WSS 3.0, MOSS 2007 and SharePoint 2010 platforms, they want to organize the structure and keep the contents similar. An ideal goal is to move to upgraded versions.

During this big discussion development team suggested to make a script which reads the web, site, lists and document library properties and set the same in each farm. Dude! writing script is easy and deploying is very easy as well. But, before we do that let’s know why properties are set differently ? Who made the decision? Business Justification is much more important so I suggested Power Users or SharePoint L1 to decide and deploy the solution.

How? Power Users like GUI based solutions they don’t want to execute console applications or scripts. As usual we picked up a call and I was shocked by listening to content manager requirement – “Need one liner cmdlet and we will create Lists and Set it’s Property. It may be one or many!” It’s that simple PowerShell reached to content managers as well. 🙂 I was happy because I am going to meet their needs in short span of time!

To kick on the demo in a catchy way. I showed them how PowerShell one liner looks like 🙂

Get-EvenNumbers -From 1 -To 10

It’s that simple to use, I haven’ t used any validation in this function very simple code which prints the even number using range operators. The function code is below

Function Get-EvenNumbers
{
    param(
    [Parameter(Mandatory = $true)]
    $From,
    [Parameter(Mandatory=$true)]
    $To
    )

    ($From..$To).ForEach({if($_ %2 -eq 0){$_}})
}
Get-EvenNumbers -From 1 -To 10

Solution for Content Managers:

Consume CSOM and build binary module using Class Library 🙂 🙂 🙂 This time I used Visual Studio 2013 just for a change 🙂

using System;
using System.Collections.Generic;
using System.Text;
using System.Security;
using System.Net;
using System.Management.Automation;
using Microsoft.SharePoint.Client;

[Cmdlet(VerbsCommon.Set,"SPListVisibility")]
public class SetSPListVisibility : Cmdlet
{
    [Parameter(Mandatory = true)]
    public string SPUrl;

    [Parameter(Mandatory = true)]
    public string SPListName;

    [Parameter(Mandatory = true)]
    public bool ListVisibility;
    protected override void ProcessRecord()
    {
        ClientContext ctx = new ClientContext(SPUrl);
        NetworkCredential credentials = CredentialCache.DefaultNetworkCredentials;
        ctx.Credentials = credentials;

        List list = ctx.Web.Lists.GetByTitle(SPListName);
        ctx.Load(list);

        list.Hidden = ListVisibility;
        list.Update();
        ctx.ExecuteQuery();
        ctx.Dispose();
    }
}

Usage (Just for Demo):

Import-Module C:\Scripts\Module\CSOM_Demo.Dll
#Hide the List
Set-SPListVisibility -SPUrl http://weburl -SPListName "PowerShell" -ListVisibility $false

#Show the List
Set-SPListVisibility -SPUrl http://weburl -SPListName "PowerShell" -ListVisibility $true

In next my next blog I will share the complete module! It’s that’s easy ! Happy SharePointing and Enjoy PowerShell 🙂 🙂 🙂

Reason: Content manager need this kind of solution for re usability. Smart Guy!