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

Introduction

In our last blog post (Part 1) we have show cased two functions which allows us to connect to SharePoint Online and retrieves list information from the site collections. Now, we will create a small PowerShell module with help.

About Modules

To learn about PowerShell Modules refer this link. We will be focusing about Script Module! Which is easy to understand and to troubleshoot as well. A script Module is nothing but valid script saved as .psm1 file and it has a structure to save. For our demo, we will save the PowerShell module is User Module path i.e “C:\Users\ChenV\Documents\WindowsPowerShell\Modules\SPOnlineModule” in which SPOnlineModule is the folder which contains .PSM1, .PSD1 file and required DLL’s. Ensure the psm1 and psd1 files are also named as SPOnlineModule.

Specific User

This is the location for installing modules for specific user “$home\Documents\WindowsPowerShell\Modules\

For All Users

This is the location for installing modules for all users “$EnvProgramFiles\WindowsPowerShell\Modules\”

Creating Modules

It’s very simple to create module but before distributing it ensure you have done the below

  • Test the Module
  • Include PowerShell Version
  • Create a Proper psd1 file
  • Include all required assemblies (In our case it’s required)
  • Include Help Files (This blog post will cover this!)
  • Create a Custom View for the Output

PSD1 File

This is psd1 file for the two functions we created named “Connect-xSPOTenant” and Get-xSPOList. I have moved all the SharePoint Online CSOM SDK Assemblies to my module folder. Just to distribute it to my clients and they don’t need to install the package. I have included the required dll in NestedModule Section.

#
# Module manifest for module 'SPOnlineModule'
#
# Generated by: Chendrayan Venkatesan
#
# Generated on: 11-5-2016
#

@{

# Script module or binary module file associated with this manifest.
RootModule = 'SPOnlineModule.psm1'

# Version number of this module.
ModuleVersion = '1.0'

# ID used to uniquely identify this module
GUID = 'c62fa4e8-d1d2-41e2-9304-af38c827dda9'

# Author of this module
Author = 'Chendrayan Venkatesan'

# Company or vendor of this module
CompanyName = 'Free Lancer'

# Copyright statement for this module
Copyright = '(c) 2016 904870. All rights reserved.'

# Description of the functionality provided by this module
Description = 'Include the Module Description.'

# Minimum version of the Windows PowerShell engine required by this module
PowerShellVersion = '5.0'

# Name of the Windows PowerShell host required by this module
# PowerShellHostName = ''

# Minimum version of the Windows PowerShell host required by this module
# PowerShellHostVersion = ''

# Minimum version of Microsoft .NET Framework required by this module
# DotNetFrameworkVersion = ''

# Minimum version of the common language runtime (CLR) required by this module
# CLRVersion = ''

# Processor architecture (None, X86, Amd64) required by this module
# ProcessorArchitecture = ''

# Modules that must be imported into the global environment prior to importing this module
# RequiredModules = @()

# Assemblies that must be loaded prior to importing this module
# RequiredAssemblies = @()

# Script files (.ps1) that are run in the caller's environment prior to importing this module.
# ScriptsToProcess = @('GetCredential.ps1')

# Type files (.ps1xml) to be loaded when importing this module
# TypesToProcess = @()

# Format files (.ps1xml) to be loaded when importing this module
# FormatsToProcess = @()

# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess
NestedModules = @('Microsoft.SharePoint.Client.dll',
                  'Microsoft.SharePoint.Client.Runtime.dll',
                  'Microsoft.Online.SharePoint.Client.Tenant.dll' ,
                  'CredentialManagement.dll')

# Functions to export from this module
FunctionsToExport = '*'

# Cmdlets to export from this module
CmdletsToExport = '*'

# Variables to export from this module
VariablesToExport = '*'

# Aliases to export from this module
AliasesToExport = '*'

# DSC resources to export from this module
# DscResourcesToExport = @()

# List of all modules packaged with this module
# ModuleList = @()

# List of all files packaged with this module
# FileList = @()

# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell.
PrivateData = @{

    PSData = @{

        # Tags applied to this module. These help with module discovery in online galleries.
        # Tags = @()

        # A URL to the license for this module.
        # LicenseUri = ''

        # A URL to the main website for this project.
        # ProjectUri = ''

        # A URL to an icon representing this module.
        # IconUri = ''

        # ReleaseNotes of this module
        # ReleaseNotes = ''

    } # End of PSData hashtable

} # End of PrivateData hashtable

# HelpInfo URI of this module
# HelpInfoURI = ''

# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix.
# DefaultCommandPrefix = ''

}

PSM1 File

We haven’t added help / comments or display view for the functions. All we did is created the module with required files. The below code is my PowerShell .psm1 file which has only two functions as I mentioned earlier.

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 {
    }
}

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 {
    }
}

Take look at the folder contents inside my module folder – And remember we named it as SPOnlineModule
2016-05-24_16-28-30 It’s good to start! Let’s try to import the module and test the functionality so we can add the requirement components which makes our module rich and easy to use.

Import-Module SPOnlineModule -Verbose

Fantastic, we can see the module loading successfully.
2016-05-24_16-32-01 always use Verbose switch to get information about the cmdlets we are loading to the session. Now, let’s see the available cmdlet by simply executing the below snippet

Get-Command -Module SPOnlineModule

and the output is shown below
2016-05-24_16-34-35 let’s skip the functionality test because we did it in our previous blog (Part 1). So we will focus on help and custom view for output formatting in this blog post. If we run the below PowerShell code we get very basic information about the cmdlet.

help Connect-xSPOTenant
help Connect-xSPOTenant -Detailed
help Connect-xSPOTenant -Examples

Something like this
2016-05-24_16-38-45 Okay enough of theory, we just need to add comment based help for our function and PowerShell will take care of the rest. To do this in our psm1 file we will include the comment based help inside the PowerShell functions like shown below

<#
.SYNOPSIS
    Short description
.DESCRIPTION
    Long description
.EXAMPLE
    C:\PS> <example usage>
    Explanation of what the example does
.INPUTS
    Inputs (if any)
.OUTPUTS
    Output (if any)
.NOTES
    General notes
#>

Just by doing this we are adding more feature to our PowerShell module and makes others to read the help before using the module. Avoids many hindrances and break dependencies at work place. Any PowerShell folks can go through the code and understand it. So, now Connect-xSPOTenant looks like below

function Connect-xSPOTenant {
<#
.SYNOPSIS
    This cmdlet is to establish connection to SharePoint Online Tenant.
.DESCRIPTION
    Prior to any other cmdlet this needs to be used. In order to perform SharePoint Online Tasks using Client Side Object Model establish the connection
    using Connect-xSPOTenant cmdlet. 
.EXAMPLE
    C:\PS> Connect-xSPOTenant -Url "https://contoso-admin.sharepoint.com"
    Prompts to enter the SharePoint Online Admin Credentials without User Name
.EXAMPLE
    C:\PS> Connect-xSPOTenant -Url "https://contoso-admin.sharepoint.com" -Credential "Admin@contoso.onmicrosoft.com"
    Prompts to enter the SharePoint Online Admin Credentials with User Name
#>
    [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 {
    }
}

which now allows us to use help at ease.
2016-05-24_16-53-24 and examples like 34334

Leave a Reply

Your email address will not be published. Required fields are marked *