Dog Food Conference 2014


Today I had the privilege of presenting on Managing SharePoint Anywhere with Windows PowerShell at Dog Food Conference, 2014!

My presentation was focused on leveraging the Microsoft.SharePoint.Client assembly to write Client Side Object Model (CSOM) code against SharePoint Online. However, the twist is that it’s all done in PowerShell 3.0 – and there is a set of PowerShell functions written specifically to handle automation in SharePoint Online.

While I have shared this topic a time or two at other events, this was the most refined version of the presentation.

Below is a description of the topic itself along with the slides used in the presentation:

Managing SharePoint Anywhere with Windows PowerShell

The story: With the growing adoption of Office 365 and SharePoint Online and the continued prevalence of SharePoint on-premises, it’s becoming more difficult to manage both environments in an automated fashion. While SharePoint Online does have native support for Windows PowerShell, there are very few cmdlets to manage the sites and site contents. SharePoint on-premises gives us well over 700 cmdlets, but it still doesn’t answer every situational scenario – leaving gaps in functionality which can be filled by scripters.

In this demo-heavy session, focused on both the developer AND the administrator – you’ll see how you can use one shell to manage both scenarios (on-premises and Office 365). Demonstrations will focus on building PowerShell Scripts and Advanced Functions for both target environments, and by the end of the session you’ll be ready to start Managing SharePoint Anywhere with PowerShell.

Here are the slides:

Code Snippets

Here are the PowerShell functions that were demonstrated:

Write-Message

Function Write-Message {
<#
.SYNOPSIS
	Use Write-Message to return a message to the console using the specified Write Type.
.DESCRIPTION
	This advanced PowerShell function uses all available Write cmdlets in the Microsoft.PowerShell.Utility module to return a specified message to the console at runtime.
.EXAMPLE
	C:\PS>Write-Message -WriteType Debug -Message "Hello World" -Debug
	This example uses Write-Debug to return the message "Hello world" to the console, this is only displayed if including the -Debug switch or setting the DebugPreference to Continue or higher.
.EXAMPLE
	C:\PS>Write-Message -WriteType Error -Message "Hello World"
	This example uses Write-Error to return the message "Hello world" to the console.
.EXAMPLE
	C:\PS>Write-Message -WriteType EventLog -Message "Hello World"
	This example uses Write-EventLog to add the message "Hello world" to the Windows Event Viewer.
.EXAMPLE
	C:\PS>Write-Message -WriteType Host -Message "Hello World" -ForegroundColor White -BackgroundColor Red
	This example uses Write-Host to return the message "Hello world" to the console.
.EXAMPLE
	C:\PS>Write-Message -WriteType Output -Message "Hello World"
	This example uses Write-Output to return the message "Hello world" to the console.
.EXAMPLE
	C:\PS>Write-Message -WriteType Progress -Message "Hello World"
	This example uses Write-Progress to return the message "Hello world" to the console, while also counting to 10 and displaying interactive progress messaging.
.EXAMPLE
	C:\PS>Write-Message -WriteType Verbose -Message "Hello World"
	This example uses Write-Verbose to return the message "Hello world" to the console, this is only displayed if including the -Verbose switch or setting the VerbosePreference to Continue or higher.
.EXAMPLE
	C:\PS>Write-Message -WriteType Warning -Message "Hello World"
	This example uses Write-Warning to return the message "Hello world" to the console.
.PARAMETER WriteType
	This parameter is required to specify the Write cmdlet the function will use. Available values are Debug, Error, EventLog, Host, Output, Progress, Verbose and Warning.
.PARAMETER Message
	This parameter is required to specify the message to be returned by the function.
.PARAMETER ForegroundColor
	This parameter is optional and will specify the foreground color for the Write-Host cmdlet.
.PARAMETER BackgroundColor
	This parameter is optional and will specify the background color for the Write-Host cmdlet.
#Requires -Version 3.0
#>
[CmdletBinding()] #Most important 1-liner in PowerShell
# Parameters
Param
(
    [Parameter(ParameterSetName="Main",
    Mandatory=$true,
	HelpMessage="Please specify the Write type.")]
    [ValidateSet('Debug','Error','EventLog','Host','Output','Progress','Verbose','Warning')]
	[alias("Type")]
	[System.String]$WriteType,

    [Parameter(ParameterSetName="Main",
    Mandatory=$true,
	HelpMessage="Please specify the Message.")]
    [alias("Text")]
	[System.String]$Message,

    [Parameter(ParameterSetName="Main",
    Mandatory=$false,
	HelpMessage="Please specify the ForegroundColor.")]
    [ValidateSet('Black','Blue','Cyan','DarkBlue','DarkCyan','DarkGray','DarkGreen','DarkMagenta','DarkRed','DarkYellow','Gray','Green','Magenta','Red','White','Yellow')]
    [alias("fgcolor")]
	[System.String]$ForegroundColor,

    [Parameter(ParameterSetName="Main",
    Mandatory=$false,
	HelpMessage="Please specify the BackgroundColor.")]
    [ValidateSet('Black','Blue','Cyan','DarkBlue','DarkCyan','DarkGray','DarkGreen','DarkMagenta','DarkRed','DarkYellow','Gray','Green','Magenta','Red','White','Yellow')]
    [alias("bgcolor")]
	[System.String]$BackgroundColor
)
    #Begin {}
    Process
    {
        Switch ($WriteType)
        {
            Debug
            {
                Write-Debug -Message $Message
            }

            Error
            {
                Write-Error -Message $Message
            }

            EventLog
            {
                Try
                {
                    Get-EventLog -LogName Application -Source MyScript -ErrorAction SilentlyContinue | Out-Null
                }
                Catch
                {
                    New-EventLog -LogName Application -Source MyScript
                }
                Finally
                {
                    Write-EventLog -LogName Application -Source MyScript -EntryType Information -Category 1 -EventId 1234 -Message $Message
                }
            }

            Host
            {
                If ($ForegroundColor -and $BackgroundColor)
                {
                    Write-Host $Message -BackgroundColor $BackgroundColor -ForegroundColor $ForegroundColor
                }
                ElseIf ($ForegroundColor -and -not ($BackgroundColor))
                {
                    Write-Host $Message -ForegroundColor $ForegroundColor
                }
                ElseIf ($BackgroundColor -and -not ($ForegroundColor))
                {
                    Write-Host $Message -BackgroundColor $BackgroundColor
                }
                Else
                {
                    Write-Host $Message
                }
            }

            Output
            {
                Write-Output $Message
            }

            Progress
            {
                $i=0
                $iMax = 10
                Do
                {
	                $i++
	                Write-Progress -Activity $Message -PercentComplete ($i/$iMax*100) -Status $i
	                Start-Sleep -Seconds 1
                }
                While ($i -lt $iMax)
            }

            Verbose
            {
                Write-Verbose -Message $Message
            }

            Warning
            {
                Write-Warning -Message $Message
            }
        } #end Switch
    } #end Process
    #End {}
} #end Write-Message Function

Get-SPOAssemblies

Function Get-SPOAssemblies {
<#
.SYNOPSIS
	Use Get-SPOAssemblies to check current assemblies loaded.
.DESCRIPTION
	This advanced PowerShell function uses the GetAssemblies method of the System.AppDomain class to return assemblies.
    If the Microsoft.SharePoint.Client and Microsoft.SharePoint.Client.Runtime assemblies are present, the function returns
    a boolean value of $True. If the assemblies are not found, $False is returned.
.EXAMPLE
	C:\PS>Get-SPOAssemblies
	This example checks for the Microsoft.SharePoint.Client and Microsoft.SharePoint.Client.Runtime assemblies in the current session.
#Requires -Version 3.0
#>
[CmdletBinding()]
Param(
[Switch]$BusinessData,
[Switch]$DocumentManagement,
[Switch]$Publishing,
[Switch]$Search,
[Switch]$SearchApplications,
[Switch]$Taxonomy,
[Switch]$UserProfiles,
[Switch]$WorkflowServices
)
    Begin
    {
        $Assemblies = ("microsoft.sharepoint.client","microsoft.sharepoint.client.runtime")
        [System.Boolean]$Loaded=$false
    }
    Process
    {
        If($BusinessData){$Assemblies += "Microsoft.SharePoint.BusinessData.Administration.Client"}
        If($DocumentManagement){$Assemblies += "Microsoft.SharePoint.Client.DocumentManagement"}
        If($Publishing){$Assemblies += "Microsoft.SharePoint.Client.Publishing"}
        If($Search){$Assemblies += "Microsoft.SharePoint.Client.Search"}
        If($SearchApplications){$Assemblies += "Microsoft.SharePoint.Client.Search.Applications"}
        If($Taxonomy){$Assemblies += "Microsoft.SharePoint.Client.Taxonomy"}
        If($UserProfiles){$Assemblies += "Microsoft.SharePoint.Client.UserProfiles"}
        If($WorkflowServices){$Assemblies += "Microsoft.SharePoint.Client.WorkflowServices.Activities"}
        $Assemblies | ForEach-Object {
            $assembly = "*$_*"
            If ([System.AppDomain]::CurrentDomain.GetAssemblies() | Where-Object {$_.Location -like $assembly})
            {
                $Loaded=$true
            }
            Else
            {
                $Loaded=$false
            }
        }
    }
    End
    {
        Return $Loaded
    }
} #end Get-SPOAssemblies

Import-SPOAssemblies

Function Import-SPOAssemblies {
<#
.SYNOPSIS
	Use Import-SPOAssemblies to load the Microsoft.SharePoint.Client and Microsoft.SharePoint.Client.Runtime assemblies into the current session.
.DESCRIPTION
	This function uses the Add-Type Cmdlet to import the Microsoft.SharePoint.Client and Microsoft.SharePoint.Client.Runtime assemblies.
.EXAMPLE
	C:\PS>Import-SPOAssemblies
	This example loads the assemblies.
.EXAMPLE
    C:\PS>Import-SPOAssemblies -Taxonomy -Search
    This example loads the Microsoft.SharePoint.Client, Microsoft.SharePoint.Client.Runtime, Microsoft.SharePoint.Client.Taxonomy and Microsoft.SharePoint.Client.Search assemblies.
.EXAMPLE
    C:\PS>Import-SPOAssemblies -BusinessData -DocumentManagement -Publishing -Search -SearchApplications -Taxonomy -UserProfiles -WorkflowServices
    This example loads all Client assemblies.
#Requires -Version 3.0
#>
[CmdletBinding()]
Param(
[Switch]$BusinessData,
[Switch]$DocumentManagement,
[Switch]$Publishing,
[Switch]$Search,
[Switch]$SearchApplications,
[Switch]$Taxonomy,
[Switch]$UserProfiles,
[Switch]$WorkflowServices
)
    Process
	{
		Try
		{
            [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client") | Out-Null
            [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime") | Out-Null
            If($BusinessData)
            {
                [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.BusinessData.Administration.Client") | Out-Null
            }
            If($DocumentManagement)
            {
                [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.DocumentManagement") | Out-Null
            }
            If($Publishing)
            {
                [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Publishing") | Out-Null
            }
            If($Search)
            {
                [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Search") | Out-Null
            }
            If($SearchApplications)
            {
                [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Search.Applications") | Out-Null
            }
            If($Taxonomy)
            {
                [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Taxonomy") | Out-Null
            }
            If($UserProfiles)
            {
                [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.UserProfiles") | Out-Null
            }
            If($WorkflowServices)
            {
                #[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.WorkflowServices.Activities") | Out-Null
                [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.WorkflowServices.Activities") | Out-Null
            }
		}
		Catch
		{
			Write-Error -Message $Error[0]
		}
	}

} #end Import-SPOAssemblies

New-SPOServiceContext

Function New-SPOServiceContext {
<#
.SYNOPSIS
	Use New-SPOServiceContext to invoke ClientContext for a SharePoint Online site.
.DESCRIPTION
	This advanced PowerShell function creates a ClientContext object for the current PowerShell session
    and stores the Context in the $GLOBAL:SPOContext object, while also creating an SPWeb object in the $GLOBAL:Web variable.
.EXAMPLE
	C:\PS>New-SPOServiceContext -EmailAddress ryan.dennis@bluechip-llc.com -WebUrl https://bluechip1.sharepoint.com
	This example creates a context object for an SPWeb at https://bluechip1.sharepeoint.com with user ryan.dennis@bluechip-llc.com.
.INPUTS
	This cmdlet supports the PowerShell pipeline.
.OUTPUTS
.PARAMETER EmailAddress
	This parameter is required to specify the user account for the context session. You will be prompted for password at runtime.
.PARAMETER WebUrl
	This parameter is required to specify the Web URL of a SharePoint Online site.
.PARAMETER UserName
    This parameter is required If using the OnPremise parameter set.
.PARAMETER OnPremise
    This optional switch parameter can be included to create a ClientContext object against an on-premise SharePoint farm.
.NOTES
	To see the examples, type: "Get-Help New-SPOServiceContext -Examples"
	To see more information, type: "Get-Help New-SPOServiceContext -Detail"
	To see technical information, type: "Get-Help New-SPOServiceContext -Full"
#Requires -Version 3.0
#>
[CmdletBinding()]
Param(
		[Parameter(ValueFromPipeline=$true,Mandatory=$true)]
		[ValidateNotNull()]
		[System.Management.Automation.PSCredential]
		[System.Management.Automation.Credential()]
		$Credential = [System.Management.Automation.PSCredential]::Empty,

		[Parameter(Mandatory=$true,
		HelpMessage="Please specify the Web URL for Context.",
		ValueFromPipeline=$true,
		ValueFromPipelineByPropertyName=$true)]
		[alias("Identity")]
		[System.String]$WebUrl,

		[Parameter(
		Mandatory=$false,
		HelpMessage="Include this switch parameter to create ClientContext against an on-premise SharePoint farm.")]
		[Switch]$OnPremise
)
        Begin
        {
            If(-not(Get-SPOAssemblies))
		    {
                Import-SPOAssemblies
		    }
			<#
			If($Password)
			{
				$pw = ConvertTo-SecureString -String $Password -AsPlainText -Force
				$creds = New-Object System.Management.Automation.PSCredential -ArgumentList $EmailAddress,$pw
			}
			#>
        }
        Process
        {
            If($OnPremise)
            {
                $GLOBAL:SPOContext = New-Object -TypeName Microsoft.SharePoint.Client.ClientContext($WebUrl)
		        $GLOBAL:SPOContext.Credentials = New-Object -TypeName System.Net.NetworkCredential ($Credential.UserName,$Credential.Password)
		        $GLOBAL:SPOWeb = $GLOBAL:SPOContext.Web
		        $GLOBAL:SPOContext.Load($GLOBAL:SPOWeb)
		        $GLOBAL:SPOContext.ExecuteQuery()
            }
            Else
            {
                [Microsoft.SharePoint.Client.ClientContext]$GLOBAL:SPOContext = New-Object -TypeName Microsoft.SharePoint.Client.ClientContext($WebUrl)
            	$GLOBAL:SPOContext.Credentials = New-Object -TypeName Microsoft.SharePoint.Client.SharePointOnlineCredentials($Credential.UserName,$Credential.Password)
				$GLOBAL:SPOWeb = $GLOBAL:SPOContext.Web
                $GLOBAL:SPOContext.Load($GLOBAL:SPOWeb)
                $GLOBAL:SPOContext.ExecuteQuery()
            }
        }
        End
        {
            Return $GLOBAL:SPOContext | Out-Null
        }
} #end New-SPOServiceContext

Get-SPOWeb

Function Get-SPOWeb {
<#
.SYNOPSIS
	Use Get-SPOWeb to retrieve an SPWeb Object using SharePoint Client Side code.
.DESCRIPTION
	This advanced function uses SharePoint Client Side Object Model (CSOM) code to store a specIfied SPWeb
    in a global variable called $GLOBAL:SPOWeb.
.EXAMPLE
	C:\PS>Get-SPOWeb -Url https://bluechip1.sharepoint.com -EmailAddress ryan.dennis@bluechip-llc.com
	This example retrieves an SPWeb at URL https://bluechip1.sharepoint.com using the credentials ryan.dennis@bluechip-llc.com.
.INPUTS
	This cmdlet supports the PowerShell pipeline.
.OUTPUTS
.PARAMETER EmailAddress
	This parameter is required to specify the user account for the context session. You will be prompted for password at runtime.
.PARAMETER WebUrl
	This parameter is required to specify the Web URL of a SharePoint Online site.
.NOTES
	To see the examples, type: "Get-Help Get-SPOWeb -Examples"
	To see more information, type: "Get-Help Get-SPOWeb -Detail"
	To see technical information, type: "Get-Help Get-SPOWeb -Full"
#Requires -Version 3.0
#>
[CmdletBinding()]
Param(
    [Parameter(Position=0,
	ParameterSetName="ByName",
	Mandatory=$true,
	HelpMessage="Please specify the Web Url.",
	ValueFromPipeline=$true,
	ValueFromPipelineByPropertyName=$true)]
	[alias("Identity")]
	[System.String]$Url,

    [Parameter(ValueFromPipeline=$true,Mandatory=$true)]
	[ValidateNotNull()]
	[System.Management.Automation.PSCredential]
	[System.Management.Automation.Credential()]
	$Credential = [System.Management.Automation.PSCredential]::Empty
)
	Begin
	{
		If(-not(Get-SPOAssemblies))
		{
            Import-SPOAssemblies
		}
	}
	Process
	{
		If(!$GLOBAL:SPOContext -or $GLOBAL:SPOContext.Url -ne $Url)
		{
			New-SPOServiceContext -WebUrl $Url -Credential $Credential
		}

		Try
	    {
	        [Microsoft.SharePoint.Client.Web]$GLOBAL:SPOWeb = $GLOBAL:SPOContext.Web
			$GLOBAL:SPOContext.Load($GLOBAL:SPOWeb)
			$GLOBAL:SPOContext.ExecuteQuery()
	    }
	    Catch
	    {
	        Write-Error -Message $Error[0]
	    }
	} #end Process
    End
    {
        If($GLOBAL:SPOWeb)
		{
	        Write-Verbose -Message 'To access properties of the SPWeb object, use the $GLOBAL:SPOWeb variable'
            Return $GLOBAL:SPOWeb | Select-Object Url
	    }
	    Else
        {
            Write-Error -Message "Unable to retrieve SPWeb object"
        }
    }
} #end Get-SPOWeb

New-SPOWeb

Function New-SPOWeb {
<#
.SYNOPSIS
	Use New-SPOWeb to create a new SharePoint website under an existing site collection.
.DESCRIPTION
	This advanced PowerShell function uses SharePoint Client Side Object Model (CSOM) code to provision a
	new SPWeb object within an existing SPSite AllWebs collection.
.EXAMPLE
	C:\PS>New-SPOWeb -Title "Team Site" -Url team-site -Description "This is a new team site" -Template "STS#0" -Language 1033
	This example will create a Team Site with a relative URL of team-site within the current site collection.
.INPUTS
	This cmdlet supports the PowerShell pipeline.
.OUTPUTS
.PARAMETER Title
	This parameter is required to specify the title of the new SharePoint web.
.PARAMETER Url
	This parameter is required to specify the relative URL of the new SharePoint web.
	If omitted, the URL will be the Site Title with no spaces.
.PARAMETER Description
	This optional parameter can be included to specify a description for the new SharePoint web.
.PARAMETER Template
	This optional parameter can be included to specify a web template. The default is Team Site (STS#0).
.PARAMETER Language
	This optional parameter can be included to specify a language. The default is English (1033).
.NOTES
	To see the examples, type: "Get-Help New-SPOWeb -Examples"
	To see more information, type: "Get-Help New-SPOWeb -Detail"
	To see technical information, type: "Get-Help New-SPOWeb -Full"
#Requires -Version 3.0
#>
[CmdletBinding()]
Param(
	[Parameter(
	Mandatory=$true,
	HelpMessage="Please specify the Web Title.",
	ValueFromPipeline=$true,
	ValueFromPipelineByPropertyName=$true)]
	[alias("Name")]
	[System.String]$Title,

    [Parameter(
	Mandatory=$true,
	HelpMessage="Please specify the Web Url.",
	ValueFromPipeline=$true,
	ValueFromPipelineByPropertyName=$true)]
	[alias("Path")]
	[System.String]$Url,

	[Parameter(
	Mandatory=$false,
	HelpMessage="Please specify the Web Description.",
	ValueFromPipeline=$true,
	ValueFromPipelineByPropertyName=$true)]
	[alias("Desc")]
	[System.String]$Description,

	[Parameter(
	Mandatory=$false,
	HelpMessage="Please specify the Web Template. To find available templates, use Get-SPOWebTemplate.",
	ValueFromPipeline=$true,
	ValueFromPipelineByPropertyName=$true)]
	[alias("WebTemplate")]
	[System.String]$Template="STS#0",

	[Parameter(
	Mandatory=$false,
	HelpMessage="Please specify the Web Language ID.",
	ValueFromPipeline=$true,
	ValueFromPipelineByPropertyName=$true)]
	[alias("LangID")]
	[System.UInt32]$Language=1033,

	[Switch]$UseSamePermissionsAsParentSite,

	[Parameter(ValueFromPipeline=$true,Mandatory=$false)]
	[ValidateNotNull()]
	[System.Management.Automation.PSCredential]
	[System.Management.Automation.Credential()]
	$Credential = [System.Management.Automation.PSCredential]::Empty,

	[System.String]$ParentSiteUrl
)

	Begin
	{
		If(-not(Get-SPOAssemblies))
		{
            Import-SPOAssemblies
		}
		$NewSPOContext = New-Object -TypeName Microsoft.SharePoint.Client.ClientContext($ParentSiteUrl)
    	$NewSPOContext.Credentials = New-Object -TypeName Microsoft.SharePoint.Client.SharePointOnlineCredentials($Credential.UserName,$Credential.Password)
		$ParentSPOWeb = $NewSPOContext.Web
        $NewSPOContext.Load($ParentSPOWeb)
        $NewSPOContext.ExecuteQuery()
	}
	Process
	{
		Try
	    {
	        $CreationInfo = New-Object -TypeName Microsoft.SharePoint.Client.WebCreationInformation
			$CreationInfo.Description = $Description
			$CreationInfo.Language = $Language
			$CreationInfo.Title = $Title
			$CreationInfo.Url = $Url
			$CreationInfo.WebTemplate = $Template
			If($UseSamePermissionsAsParentSite)
			{
				$CreationInfo.UseSamePermissionsAsParentSite = $true
			}
			[Microsoft.SharePoint.Client.Web]$NewSPOWeb = $NewSPOContext.Web.Webs.Add($CreationInfo)
			$NewSPOContext.Load($NewSPOWeb)
			$NewSPOContext.ExecuteQuery()
	    }
	    Catch
	    {
	        Write-Error -Message $Error[0]
	    }
	} #end Process
    End
    {

    }
} #end New-SPOWeb

Remove-SPOWeb

Function Remove-SPOWeb {
<#
.SYNOPSIS
	Use Remove-SPOWeb to delete a SharePoint Online website under an existing site collection.
.DESCRIPTION
	This advanced PowerShell function uses SharePoint Client Side Object Model (CSOM) code to delete an
	SPWeb object from an existing SPSite AllWebs collection.
.EXAMPLE
	C:\PS>Remove-SPOWeb -Url https://bluechip1.sharepoint.com/subsite -EmailAddress ryan.dennis@bluechip-llc.com
	This example will delete a site with a relative URL of subsite within the https://bluechip1.sharepoint.com site collection.
.INPUTS
	This cmdlet supports the PowerShell pipeline.
.OUTPUTS
.PARAMETER Url
	This parameter is required to specify the relative URL of the SharePoint web.
.PARAMETER EmailAddress
	This parameter is required to specify the user account for the context session. You will be prompted for password at runtime.
.NOTES
	To see the examples, type: "Get-Help Remove-SPOWeb -Examples"
	To see more information, type: "Get-Help Remove-SPOWeb -Detail"
	To see technical information, type: "Get-Help Remove-SPOWeb -Full"
#Requires -Version 3.0
#>
[CmdletBinding(SupportsShouldProcess=$true,ConfirmImpact="High")]
Param(
    [Parameter(Position=0,
	ParameterSetName="ByName",
	Mandatory=$true,
	HelpMessage="Please specify the Web Url.",
	ValueFromPipeline=$true,
	ValueFromPipelineByPropertyName=$true)]
	[alias("Identity")]
	[System.String]$Url,

	[Parameter(ValueFromPipeline=$true,Mandatory=$true)]
	[ValidateNotNull()]
	[System.Management.Automation.PSCredential]
	[System.Management.Automation.Credential()]
	$Credential = [System.Management.Automation.PSCredential]::Empty
)

	Begin
	{
        If(-not(Get-SPOAssemblies))
		{
            Import-SPOAssemblies
		}
		[Microsoft.SharePoint.Client.ClientContext]$RemoveContext = New-Object -TypeName Microsoft.SharePoint.Client.ClientContext($Url)
		#$RemoveCredentials = Get-Credential -UserName $EmailAddress -Message "Please enter your Office 365 Password"
		$RemoveContext.Credentials = New-Object -TypeName Microsoft.SharePoint.Client.SharePointOnlineCredentials($Credential.UserName,$Credential.Password)
	}
	Process
	{
		Try
	    {
	        If($PSCmdlet.ShouldProcess($Url))
			{
			    $RemoveWeb = $RemoveContext.Web
			    $RemoveWeb.DeleteObject()
				$RemoveContext.ExecuteQuery()
			}
	    }
	    Catch
	    {
	        Write-Error -Message $Error[0]
	    }
	} #end Process
    End
    {
        Write-Verbose -Message "Web $Url deleted successfully"
    }
} #end Remove-SPOWeb

New-SPOList

Function New-SPOList {
<#
.SYNOPSIS
	Use New-SPOList to create a new SharePoint List or Library.
.DESCRIPTION
	This advanced PowerShell function uses the Add method of a SPWeb object to create new lists and libraries in a SharePoint Web.
.EXAMPLE
	C:\PS>New-SPOList -ListTitle "My Documents" -ListUrl "MyDocuments" -Description "This is my library" -Template "Document Library"
	This example creates a standard Document Library in the http://intranet site.
.EXAMPLE
	C:\PS>New-SPOList -ListTitle "My Announcements" -ListUrl "MyAnnouncements" -Description "These are company-wide announcements." -Template "Announcements"
	This example creates an Announcements list in the http://intranet site.
.INPUTS
	This cmdlet supports the PowerShell pipeline.
.OUTPUTS
.PARAMETER ListTitle
	This parameter is required to specify the title of the new SPList.
.PARAMETER ListUrl
	This parameter is required to specify the relative URL of the new SPList.
.PARAMETER Description
	This optional parameter can be included to provide a description for the new SPList.
.PARAMETER Template
	This parameter is required to specify the List Template for the new SPList.
.PARAMETER OnQuickLaunch
	This optional parameter can be included to include the new SPList on the Quick Launch of the current Site.
.PARAMETER Hidden
    This optional parameter can be included to specify the list as a hidden list.
.NOTES
	To see the examples, type: "Get-Help New-SPOList -Examples"
	To see more information, type: "Get-Help New-SPOList -Detail"
	To see technical information, type: "Get-Help New-SPOList -Full"
#Requires -Version 3.0
#>
[CmdletBinding()]
Param(
	[Parameter(
	ParameterSetName="ByName",
	Mandatory=$true,
	HelpMessage="Please specify the List Title.",
	ValueFromPipeline=$true,
	ValueFromPipelineByPropertyName=$true)]
	[alias("Title")]
	[System.String]$Name,

    [Parameter(
	ParameterSetName="ByName",
	Mandatory=$false,
	HelpMessage="Please specify the List Url.",
	ValueFromPipeline=$true,
	ValueFromPipelineByPropertyName=$true)]
	[alias("ListPath")]
	[System.String]$ListUrl,

	[Parameter(
	ParameterSetName="ByName",
	Mandatory=$false,
	HelpMessage="Please specify the List Description.",
	ValueFromPipeline=$true,
	ValueFromPipelineByPropertyName=$true)]
	[alias("Desc")]
	[System.String]$Description,

	[Parameter(
	ParameterSetName="ByName",
	Mandatory=$true,
	HelpMessage="Please specify the List Template. To see available templates, use the Get-SPOListTemplates function.",
	ValueFromPipeline=$true,
	ValueFromPipelineByPropertyName=$true)]
    [ValidateSet('AccessRequest','AdminTasks','Agenda','Announcements','AppDataCatalog',
    'CallTrack','Categories','Circulation','Comments','Contacts','CustomGrid','DataConnectionLibrary',
    'DataSources','Decision','DesignCatalog','DeveloperSiteDraftApps','DiscussionBoard',
    'DocumentLibrary','Events','ExternalList','Facility','GanttTasks','GenericList','HealthReports',
    'HealthRules','HelpLibrary','Holidays','HomePageLibrary','IMEDic','InvalidType','IssueTracking',
    'Links','ListTemplateCatalog','MaintenanceLogs','MasterPageCatalog','MeetingObjective',
    'Meetings','MeetingUser','MySiteDocumentLibrary','NoCodePublic','NoCodeWorkflows','NoListTemplate',
    'PictureLibrary','Posts','SolutionCatalog','Survey','Tasks','TasksWithTimelineAndHierarchy',
    'TextBox','ThemeCatalog','ThingsToBring','Timecard','UserInformation','WebPageLibrary',
    'WebPartCatalog','WebTemplateCatalog','Whereabouts','WorkflowHistory','WorkflowProcess','XMLForm')]
	[alias("ListTemplate")]
	[System.String]$Type,

	[Parameter(
	ParameterSetName="ByName",
	Mandatory=$false,
	HelpMessage="Include this parameter to display this list on the quick launch.",
	ValueFromPipeline=$true,
	ValueFromPipelineByPropertyName=$true)]
	[alias("OnLeftNav")]
	[Switch]$ShowOnQuickLaunch,

    [Parameter(
	ParameterSetName="ByName",
	Mandatory=$false,
	HelpMessage="Include this parameter to set this list as hidden.",
	ValueFromPipeline=$true,
	ValueFromPipelineByPropertyName=$true)]
	[alias("Hide")]
	[Switch]$Hidden,

    [Parameter(
	ParameterSetName="ByName",
	Mandatory=$false,
	HelpMessage="Please specify the content type of the library.",
	ValueFromPipeline=$true,
	ValueFromPipelineByPropertyName=$true)]
	$ContentType,

	[Parameter(
	ParameterSetName="ByName",
	Mandatory=$false,
	HelpMessage="Please specify the draft item security of the library.",
	ValueFromPipeline=$true,
	ValueFromPipelineByPropertyName=$true)]
	[ValidateSet('Reader','Author','Approver')]
	$DraftItemSecurity,		

	[Parameter(
	Mandatory=$false,
	ParameterSetName="ByName")]
	[switch]$EnableVersioning,

	[Parameter(
	Mandatory=$false,
	ParameterSetName="ByName")]
	[switch]$EnableMinorVersioning,

	[Parameter(
	Mandatory=$false,
	ParameterSetName="ByName")]
	[switch]$EnableModeration,

	[Parameter(
	Mandatory=$false,
	ParameterSetName="ByName")]
	[switch]$BreakRoleInheritance,

	[Parameter(
	Mandatory=$false,
	ParameterSetName="ByName")]
	[switch]$CopyRoleAssignments
)

	Begin
	{
		If(-not(Get-SPOAssemblies))
		{
            Import-SPOAssemblies
		}
	}
	Process
	{
		If(!$GLOBAL:SPOContext)
		{
			New-SPOServiceContext
		}
		Try
	    {
	        $CreationInfo = New-Object -TypeName Microsoft.SharePoint.Client.ListCreationInformation
			$CreationInfo.Description = $Description
			$CreationInfo.Title = $Name
			If($ListUrl)
            {
                $CreationInfo.Url = $ListUrl
            }
			Else
            {
                $CreationInfo.Url = $Name.Replace(" ","")
            }
			$CreationInfo.TemplateType = [Microsoft.SharePoint.Client.ListTemplateType]::$Type
			$List = $GLOBAL:SPOWeb.Lists.Add($CreationInfo)
            If($Hidden)
            {
                $List.Hidden = $true
            }
            If($DraftItemSecurity)
            {
                Switch ($DraftItemSecurity)
				{
				    "Reader" { $List.DraftVersionVisibility = [Microsoft.SharePoint.Client.DraftVisibilityType]::Reader }
				    "Author" { $List.DraftVersionVisibility = [Microsoft.SharePoint.Client.DraftVisibilityType]::Author }
				    "Approver" { $List.DraftVersionVisibility = [Microsoft.SharePoint.Client.DraftVisibilityType]::Approver }
				}
                Write-Debug -Message  "Updated Draft Item Security"
            }
            If($EnableVersioning)
            {
                $List.EnableVersioning = $true
            }
            If($EnableMinorVersioning)
            {
                $List.EnableMinorVersions = $true
            }
            If($EnableModeration)
            {
                $List.EnableModeration = $true
            }
            If($BreakRoleInheritance)
            {
                $List.BreakRoleInheritance($CopyRoleAssignments)
            }
            If($ShowOnQuickLaunch)
            {
                $List.OnQuickLaunch = $true
            }
            $List.Update()
            $GLOBAL:SPOContext.ExecuteQuery()
            Write-Debug -Message  "List has been created"
            If($ContentType)
            {
                # The following command will add a global variable called $Global:SPOContentType
                Get-SPOContentType -Name $ContentType | Out-Null
                Write-Debug -Message  "Retrieved content type $Global:SPOContentType"
                If($Global:SPOContentType.Name -ne $null -and $Global:SPOContentType.Name -eq $ContentType)
                {
                    $NewCT = $List.ContentTypes.AddExistingContentType($Global:SPOContentType)
                    <# Write-Debug -Message  "Added content type to list"
                    If ($List.BaseType -eq "DocumentLibrary")
                    {
					    $ListCTs = $List.ContentTypes
                        $GLOBAL:SPOContext.Load($ListCTs)
                        $GLOBAL:SPOContext.ExecuteQuery()
                        ($ListCTs | Where-Object {$_.Name -eq 'Document'}).DeleteObject()
                        Write-Debug -Message  "Removed Document content type"
					} #>
                    $List.Update()
                    $GLOBAL:SPOContext.ExecuteQuery()
                }
            }
	    }
	    Catch
	    {
	        Write-Error -Message $Error[0]
	    } #end Catch
	} #end Process
	End
	{
		$GLOBAL:SPOContext.Dispose()
	}
} #end New-SPOList
Advertisements

4 thoughts on “Dog Food Conference 2014

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s