PowerShell SharePoint tutorial with examples

This PowerShell SharePoint tutorial, we will see a few useful examples to work with SharePoint 2010/2013/2016 or SharePoint Online.

For a few examples, we are also going to use CSOM with PowerShell in SharePoint Online Office 365.

PowerShell SharePoint tutorial

If you are new to PowerShell SharePoint, check out an article on Working with PowerShell in SharePoint Online/2016/2013. We can write, debug and test our PowerShell script either using Visual Studio Code or Windows PowerShell ISE.

Below are a few PowerShell SharePoint tutorials with examples.

Create Site Collection PowerShell Script SharePoint 2016/2013/2010

This SharePoint PowerShell example we will see, how to create a site collection using PowerShell script in SharePoint 2016/2013/2010.

So here we will read the SharePoint site details from a CSV file and then we will create a site collection using PowerShell.

Create Site collection provided by the below inputs in CSV files.

  • SiteCollectionName
  • SiteCollectionDescription
  • SiteCollectionURL
  • SiteCollectionTemplate
  • SiteCollectionLanguage
  • SiteCollectionDatabaseName
  • PrimaryOwner
  • SecondaryOwner
  • WebApplicationURL

Please find the attached CSV files which will be used in the PS file. The PowerShell script, you can write, test and debug using Windows PowerShell ISE or by using Visual Studio code.

Below is the PowerShell script to create a SharePoint site collection.

$0 = $MyInvocation.MyCommand.Definition
$dp0 = [System.IO.Path]::GetDirectoryName($0)
$path = $(“$dp0\CreateSiteCollectionsWithContentDB.csv”)
$csv = Import-csv -path $path

foreach($line in $csv)
{
$WebApplicationURL = $line.WebApplicationURL
$SiteCollectionName = $line.SiteCollectionName
$SiteCollectionURL = $line.SiteCollectionURL
$SiteCollectionTemplate = $line.SiteCollectionTemplate
$SiteCollectionLanguage = $line.SiteCollectionLanguage
$SiteCollectionDatabaseName = $line.SiteCollectionDatabaseName
$PrimaryOwner = $line.PrimaryOwner
$SecondaryOwner = $line.SecondaryOwner
$SiteCollectionDescription = $line.SiteCollectionDescription

# Create a new Content Database for Sharepoint Site Collection

if ((Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null)
{
Add-PSSnapin Microsoft.SharePoint.PowerShell
}

[System.Reflection.Assembly]::LoadWithPartialName(“Microsoft.SharePoint”) | Out-null
# Get Content db from Database instance
$ContentDB = Get-SPContentDatabase $SiteCollectionDatabaseName -ErrorAction SilentlyContinue
# if content db already exists
if($ContentDB.Name -ne $null)
{
Write-Host -ForegroundColor Red “Content Database: $SiteCollectionDatabaseName already Exists”.
}
else
{
Write-Host -ForegroundColor Yellow “Content Database Does Not Exist, Creating Content Database $SiteCollectionDatabaseName ….”
$ContentDataBase=New-SPContentDatabase -name $SiteCollectionDatabaseName -WebApplication $WebApplicationURL
Write-Host -ForegroundColor Green “Content DataBase: $ContentDataBase created successfully”

# Create a new Sharepoint Site Collection

$Site=Get-SPWeb $SiteCollectionURL -ErrorAction SilentlyContinue

# check whether site collection already exists
if($Site -ne $null)
{
Write-Host “Site Collection: $Site already Exists”.
}
else
{
Write-Host -ForegroundColor Yellow “Site Collection Does Not Exist, Creating Site Collection $Site ….”
$SiteCollection=New-SPSite -URL $SiteCollectionURL -ContentDataBase $SiteCollectionDatabaseName -OwnerAlias $PrimaryOwner -SecondaryOwnerAlias $SecondaryOwner -Language $SiteCollectionLanguage -Template $SiteCollectionTemplate -Name $SiteCollectionName -Description $SiteCollectionDescription
Write-Host -ForegroundColor Green “Site Collection: $SiteCollection created successfully”
}
}
}

This way we can create a site collection using PowerShell in SharePoint 2013/2016/2010.

Create Host Named Site Collections in SharePoint Server 2013/2016/2019 using PowerShell

We had a requirement in SharePoint to create a site collection with a friendly URL. Before we move to the solution, I would like to explain about Host-named site collections and Path-based site collections.

Using Windows PowerShell script we can create hosted named site collection, which has to be assigned to a unique DNS name.

Eg. In SharePoint Administrator when we create a new site the host URL will be http://portal.Test.Com/sites/TeamA. So here the host is http://portal.Test.Com which has the same DNS record for it. But what if we had to create a site collection named ashttp:/hr.Test.com?

In SharePoint Administrator, we will not find any option to create hosted named site collection and as mentioned above we can using Windows PowerShell. So this is what we called Host-named site collections.

Path-based site collections are the regular way of creating a site collection using SharePoint Administrator or Windows PowerShell.

In Path-based, the site collection URLs will be http://portal.test.com/sites/site1, http://portal.test.com/sites/site2, etc.

All the site collections will have the same hostname and DNS name as per the web application.

Now we have a little bit of understanding about Host-named site collections and Path-based site collections.

Below Windows PowerShell script can be used to create Host-named site collections.

New-SPSite http://hr.test.com –OwnerAlias "Test\sam" –HostHeaderWebApplication http://portal.tes.com –Name "Sam Site" -Template "STS#0"

Now the site is created and we need to have DNS record entry for the same. The DNS record will be pointing to the place where SharePoint farm DNS entries are being maintained.

Enable Site and Web Features using CSOM PowerShell in SharePoint Online

Now, we will see how to enable or activate web and site features using CSOM and PowerShell script. I am following the same structure keeping the input values in the XML file and run the script.

Below is the PowerShell script to enable Site and Web Features using CSOM PowerShell in SharePoint Online

cls

$0 = $MyInvocation.MyCommand.Definition
$dp0 = [System.IO.Path]::GetDirectoryName($0)
$xmlFilePath = $("$dp0\Inputs.xml")
$xmldata = [xml](Get-Content($xmlFilePath));
$username = "samtest@microsoft.com"
$password = Read-Host -Prompt "Please enter your password" -AsSecureString
$url = $xmldata.WebSite.Url
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
$clientContext = New-Object Microsoft.SharePoint.Client.ClientContext($url)
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $securePassword)
$clientContext.Credentials = $credentials

Add-Type -Path "C:\Lib\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Lib\Microsoft.SharePoint.Client.Runtime.dll"
Add-Type -Path "C:\Lib\Microsoft.SharePoint.Client.Publishing.dll"
Add-Type -Path "C:\Lib\Microsoft.SharePoint.Client.Taxonomy.dll"

if (!$clientContext.ServerObjectIsNull.Value)
{
Write-Host "Connected to SharePoint Online site: ‘$Url'" -ForegroundColor Green
$web = $clientContext.Web
$clientContext.Load($web)
$clientContext.ExecuteQuery()
}
function AddFeature([Microsoft.SharePoint.Client.Web] $web)
{
foreach ($FeatureSite in $xmldata.WebSite.FeaturesID.FeatureSite)
{
$featureIdSite = $FeatureSite.ID
$fId = [GUID]$featureIdSite
Enable-Feature $fId $True $FeatureSite.Scope
}
}
function Enable-Feature
{
[CmdletBinding()]
param
(
[Parameter(Mandatory=$true, Position=1)]
[string]$featureId,
[Parameter(Mandatory=$true, Position=2)]
[bool]$force,
[Parameter(Mandatory=$true, Position=3)]
[Microsoft.SharePoint.Client.FeatureDefinitionScope]$featureDefinitionScope
)
Write-Host "Enabling feature $featureId on $featureDefinitionScope" -foregroundcolor black -backgroundcolor yellow
$featureGuid = new-object System.Guid $featureId
$features = $null
if ($featureDefinitionScope -eq [Microsoft.SharePoint.Client.FeatureDefinitionScope]::Site)
{
$features = $clientContext.Site.Features
} else {
$features = $clientContext.Web.Features
}
$clientContext.Load($features)
$clientContext.ExecuteQuery()
$feature = $features.Add($featureGuid, $force, [Microsoft.SharePoint.Client.FeatureDefinitionScope]::None)
# TODO: Check if the feature is already enabled
$clientContext.ExecuteQuery()

Write-Host "Feature succesfully enabled" -foregroundcolor black -backgroundcolor green
}
AddFeature $web

XML Input Entries-

<?xml version="1.0″ encoding="utf-8″?>
<WebSite Url="https://microsft.sharepoint.com/sites/test/" >
<FeaturesID>
<FeatureSite ID="f6924d36-2fa8-4f0b-b16d-06b7250180fa" Scope="Site">
</FeatureSite>
<FeatureSite ID="22a9ef51-737b-4ff2-9346-694633fe4416″ Scope="Web">
</FeatureSite>
</FeaturesID>
</WebSite>

This is how we can activate features using PowerShell in SharePoint Online Office 365.

Create Content Type and respective fields using PowerShell in SharePoint Online Office 365

Office 365 scripting is really interesting. Today I will be sharing PowerShell script to create Content type and respective site columns and also add content pages library in SharePoint Online Office 365.

Below code for PowerShell script and XML inputs respectively.

XML Inputs –

<ContentTypes>
<ContentType ParentId="0x010100C568DB52D9D0A14D9B2FDCC96666E9F2007948130EC3DB064584E219954237AF39"
Name="Contenttype1" Group="Custom Content Types" List="Pages">
<Field
RichText="FALSE" NumLines="50"
UnlimitedLengthInDocumentLibrary="TRUE"
Type="Note" DisplayName="Test Description" Required="False"
StaticName="TestDescription" Name="TestDescription" Group="Custom Columns" />
<Field
StaticName="TestImage"
Name="TestImage" DisplayName="test Image" Type="Image" Required="False" RichText="TRUE" RichTextMode="ThemeHtml" Group="Custom Columns"/>
<Field
Name="Choiceclm"
DisplayName="Test Choice column"
Type="Choice"
Required="False" StaticName="Choiceclm" Group="Custom Columns">
<CHOICES>
<CHOICE>Internal</CHOICE>
<CHOICE>External</CHOICE>
</CHOICES>
</Field>

<Field
Type="Text" DisplayName="Test Title"
Required="False" MaxLength="255"
StaticName="TestTitle"
Name="TestTitle" Group="Custom Columns" />
<Field
StaticName="TestURL" Name="TestURL"
DisplayName="Test URL" Type="URL" Format="Hyperlink" Required="False" Group="Custom Columns"/>
</ContentType>
</ContentTypes>

PowerShell Script to create a content type and required fields in SharePoint Online Office 365.

cls

$0 = $MyInvocation.MyCommand.Definition
$dp0 = [System.IO.Path]::GetDirectoryName($0)
$xmlFilePath = $(“$dp0\Inputs.xml")
$xmldata = [xml](Get-Content($xmlFilePath));

$username = “samtest@microsoft.com"
$password = Read-Host -Prompt “Please enter your password" -AsSecureString

$url = $xmldata.WebSite.Url

$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
$clientContext = New-Object Microsoft.SharePoint.Client.ClientContext($url)
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $securePassword)
$clientContext.Credentials = $credentials

Add-Type -Path “C:\Lib\Microsoft.SharePoint.Client.dll"
Add-Type -Path “C:\Lib\Microsoft.SharePoint.Client.Runtime.dll"
Add-Type -Path “C:\Lib\Microsoft.SharePoint.Client.Publishing.dll"
Add-Type -Path “C:\Lib\Microsoft.SharePoint.Client.Taxonomy.dll"

if (!$clientContext.ServerObjectIsNull.Value)
{
Write-Host “Connected to SharePoint Online site: ‘$Url'" -ForegroundColor Green
$web = $clientContext.Web
$clientContext.Load($web)
$clientContext.ExecuteQuery()
}

function createContentTypes([Microsoft.SharePoint.Client.Web] $currentWeb)
{
$web = $clientContext.Site.RootWeb
$clientContext.Load($web)
$clientContext.ExecuteQuery()

$contentTypes = $web.ContentTypes;
$clientContext.Load($contentTypes);
$clientContext.ExecuteQuery();

foreach($content in $xmldata.WebSite.ContentTypes.ContentType)
{

$docCT = $contentTypes.GetById($content.ParentId)
$clientContext.Load($docCT);
$clientContext.ExecuteQuery();

#Create a Content Type Information object
$cType = New-Object Microsoft.SharePoint.Client.ContentTypeCreationInformation

#Set the name for the content type
$cType.Name =$content.Name

#Inherit from oob document – 0x0101 and assign
$cType.ParentContentType = $docCT ;
$cType.Group = $content.Group

##Create the content type
$spCT = $contentTypes.Add($cType)
$clientContext.Load($spCT);
$clientContext.ExecuteQuery()

foreach ($node in $content.Field) {

$field=$web.Fields.AddFieldAsXml($node.OuterXml,$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldInternalNameHint);
# Finally, add the custom site column to our custom content typ$fieldReferenceLink = New-Object Microsoft.SharePoint.Client.FieldLinkCreationInformation

$fieldReferenceLink = New-Object Microsoft.SharePoint.Client.FieldLinkCreationInformation
$fieldReferenceLink.Field = $field;
$spCT.FieldLinks.Add($fieldReferenceLink)
}

# Commit changes to SharePoint
$spCT.Update($true)
$clientContext.ExecuteQuery()

$list = $currentWeb.Lists.GetByTitle($content.List)
$cts = $list.ContentTypes
$clientContext.Load($cts)

$ctReturn = $cts.AddExistingContentType($spCT)
$clientContext.Load($ctReturn)
$clientContext.ExecuteQuery()

}
}

createContentTypes $web

This is how we can create a content type and respective fields using PowerShell in SharePoint Online Office 365.

Create SharePoint 2013 List using out of box or custom template using PowerShell

Recently we had some requirements to create a list in 30 sites and subsites in SharePoint 2013. We created the list and saved the list as a template. Now creating the same list in 30 sites and subsites is a big pain. So thought of writing PowerShell script which will create the list using out of the box template or custom list template.

Here we will see how to create a list by using a custom list template in SharePoint 2013. The PowerShell script, you can write, test and debug using Windows PowerShell ISE or by using Visual Studio code.

We need to create a CSV file with the below columns as input variables.

  • SiteURL
  • TemplateName
  • ListName
  • CustomTemplate – If it’s a custom template we have to pass a parameter as Yes or if you are using OOTB template pass the parameter value as No.

So the CSV will look like the below image.

Create SharePoint 2013 List using powershell

Below is the PowerShell script to create a list form a custom list template in SharePoint 2013/2016.

$0 = $MyInvocation.MyCommand.Definition
$dp0 = [System.IO.Path]::GetDirectoryName($0)
$path = $(“$dp0\CreateListsFromTemplates.csv”)

$csv = Import-csv -path $path

foreach($line in $csv)
{
$strWebURL = $line.SiteURL
$customListTemplate = $line.CustomTemplate
if ( (Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null )
{
Add-PSSnapin Microsoft.SharePoint.PowerShell
}

[System.Reflection.Assembly]::LoadWithPartialName(“Microsoft.SharePoint”) | Out-null

$web = Get-SPWeb $strWebURL
$site = $web.Site

$rootweb = $site.OpenWeb()
if($customListTemplate.ToLower() -eq “no”)
{
write-host “List Template: ” $line.TemplateName
$web.Lists.Add($line.ListName, “”, $line.TemplateName)
Write-Host $line.ListName ” list created Successfully…..”
}
else
{
$listTemplates = $site.GetCustomListTemplates($rootweb)
$web.Lists.Add($line.ListName, “”, $listTemplates[$line.TemplateName])
Write-Host $line.ListName ” list created Successfully…..”
}
$web.Dispose()
$rootweb.Dispose()
$site.Dispose()
}

This is how we can create a list form a custom list template in SharePoint 2013/2016.

Delete SharePoint 2013 List and Library using PowerShell

Now, we will see the PowerShell script to delete the list and Libraries using PowerShell Script for SharePoint 2010 and SharePoint 2013.

Here we have a CSV file where SiteURL and ListName are presented and we will read from CSV file. Please Create a CSV file with the below columns.

  • SiteURL
  • ListName
delete SharePoint 2013 List using powershell

Below Script you can use to delete SharePoint list and libraries based on an input CSV file.

#Reading the CSV file
$path = "c:\ListAndLib.csv"
$csv = Import-csv -path $path

foreach($line in $csv)
{
#Reading content type related information
$siteURL = $line.SiteURL
$listName = $line.ListName

if ($siteURL -ne $null)
{
if ( (Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null )
{
Add-PSSnapin Microsoft.SharePoint.PowerShell
}
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint") | Out-null
# Creating the instance for site
$web = Get-SPWeb $siteURL
$list = $web.Lists[$listName]

if($list -ne $null)
{
$web.Lists.Delete([System.Guid]$list.ID)
write-host -ForegroundColor Green $listname " list has been deleted successfully…."
$web.Dispose()
}
}
}

This is how we can delete a SharePoint list or document library using PowerShell in SharePoint 2013/2016.

Create Folders inside SharePoint document library using CSOM PowerShell

Now, we will discuss how to create a folder inside a SharePoint Online document library using CSOM PowerShell.

We might have requirements to create folders inside List, Libraries, picture library or any list. We know the process to create a folder out of the box for any list which is quite simple. Here I will be sharing code to create folders in lists/libraries using PowerShell which is quite simple.

Below is the PowerShell script to create folders inside the SharePoint list or document libraries in SharePoint Online.

cls

$0 = $MyInvocation.MyCommand.Definition
$dp0 = [System.IO.Path]::GetDirectoryName($0)
$xmlFilePath = $("$dp0\Inputs.xml")
$xmldata = [xml](Get-Content($xmlFilePath));
$username = "samtest@microsoft.com"
$password = Read-Host -Prompt "Please enter your password" -AsSecureString
$url = $xmldata.WebSite.Url
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
$clientContext = New-Object Microsoft.SharePoint.Client.ClientContext($url)
$credentials = New-ObjectMicrosoft.SharePoint.Client.SharePointOnlineCredentials($username,$securePassword)
$clientContext.Credentials = $credentials

Add-Type -Path "C:\Lib\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Lib\Microsoft.SharePoint.Client.Runtime.dll"
Add-Type -Path "C:\Lib\Microsoft.SharePoint.Client.Publishing.dll"
Add-Type -Path "C:\Lib\Microsoft.SharePoint.Client.Taxonomy.dll"

if (!$clientContext.ServerObjectIsNull.Value)
{
Write-Host "Connected to SharePoint Online site: ‘$Url'" -ForegroundColorGreen
$web = $clientContext.Web
$clientContext.Load($web)
$clientContext.ExecuteQuery()
}

function CreateFolders([Microsoft.SharePoint.Client.Web] $web)
{
foreach($folderPath in $xmldata.WebSite.Folders.Folder)
{
# Create a new folder
$folder=$web.Folders.Add($folderPath.Path);
$clientContext.Load($folder);
# Execute the query
$clientContext.ExecuteQuery();
Write-Host -ForegroundColor Green "Folder Name: " $folder.Name " URL: "$folder.ServerRelativeUrl;
}
Write-Host "Folders Created by Sam"
}

CreateFolders $web

XML Inputs –

<?xml version="1.0″ encoding="utf-8″?>
<WebSite Url="https://microsft.sharepoint.com/sites/test/" >
<Folders>
<Folder Path="Pages/Folder1″></Folder>
<Folder Path="Pages/Folder2″></Folder>
<Folder Path="Lists/ImageLibrary/Folder1″></Folder>
</Folders>
</WebSite>

This is how we can create folders inside the SharePoint Online list or document libraries using PowerShell.

Create SharePoint list view using CSOM PowerShell in SharePoint Online

Now, I will be sharing code to create a view in SharePoint lists/libraries and include required columns in the view using CSOM and PowerShell scripts in SharePoint Online Office 365.

Please find below Script and input XML file to create a SharePoint list view using PowerShell.

cls

$0 = $MyInvocation.MyCommand.Definition
$dp0 = [System.IO.Path]::GetDirectoryName($0)
$xmlFilePath = $("$dp0\Inputs.xml")
$xmldata = [xml](Get-Content($xmlFilePath));

$username = "samtest@microsoft.com"
$password = Read-Host -Prompt "Please enter your password" -AsSecureString
$url = $xmldata.WebSite.Url
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
$clientContext = New-Object Microsoft.SharePoint.Client.ClientContext($url)
$credentials = New-ObjectMicrosoft.SharePoint.Client.SharePointOnlineCredentials($username, $securePassword)
$clientContext.Credentials = $credentials

Add-Type -Path "C:\Lib\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Lib\Microsoft.SharePoint.Client.Runtime.dll"
Add-Type -Path "C:\Lib\Microsoft.SharePoint.Client.Publishing.dll"
Add-Type -Path "C:\Lib\Microsoft.SharePoint.Client.Taxonomy.dll"

if (!$clientContext.ServerObjectIsNull.Value)
{
Write-Host "Connected to SharePoint Online site: ‘$Url'" -ForegroundColor Green
$web = $clientContext.Web
$clientContext.Load($web)
$clientContext.ExecuteQuery()
}

function createViews([Microsoft.SharePoint.Client.Web] $web)
{
foreach($view in $xmldata.WebSite.Views.View)
{
$pageList = $web.Lists.GetByTitle($view.List)
$clientContext.Load($pageList)
$clientContext.ExecuteQuery()

$pageViews=$pageList.Views
$clientContext.Load($pageViews)
$clientContext.ExecuteQuery()

$viewFields = New-Object System.Collections.Specialized.StringCollection

foreach($field in $view.Field){
$viewFields.Add($field.Name)
}

$viewQuery = "<Where><Gt><FieldRef Name=’ID’/><Value Type=’Counter’>0</Value></Gt></Where>"

$ViewInfo = New-Object Microsoft.SharePoint.Client.ViewCreationInformation
$ViewInfo.ViewTypeKind =[Microsoft.SharePoint.Client.ViewType]::Html
$ViewInfo.Query = $viewQuery
$ViewInfo.RowLimit = 50
$ViewInfo.ViewFields = $viewFields
$ViewInfo.Title = $view.Title
$ViewInfo.Paged = $true
$ViewInfo.PersonalView = $false

$addi=$pageList.Views.Add($ViewInfo)
$clientContext.Load($pageList)
$clientContext.ExecuteQuery()
}

}
createViews $web

XML Input:

<?xml version="1.0″ encoding="utf-8″?>
<WebSite Url="https://microsft.sharepoint.com/sites/test/" >
<Views>
<View List="Pages" Title="Sample View" >
<Field Name="LinkFilename"/>
<Field Name="Title"/>
<Field Name="Test1″/>
</View>

<View List="Pages" Title="Sample2 View" >
<Field Name="LinkFilename"/>
<Field Name="Title"/>
<Field Name="Modified"/>
</View>
</Views>
</WebSite>

You can add multiple Views nodes and add Field tags.

This is how we can create SharePoint Online list views and add fields into the views using PowerShell in SharePoint Online.

How to add web parts programmatically using PowerShell in SharePoint 2013/2016/Online

Now, we will see how to add web parts to a web part page programmatically using CSOM PowerShell in SharePoint Online.

Adding web parts programmatically to a SharePoint web part Page / Publishing page using CSOM and PowerShell Script for Office 365/SharePoint Online/SharePoint 2013. Below I will be sharing .ps script and XML input fields. In your project folder named as Web parts and the folder name will be specified XML file.

Create multiple < Webpart> tag provided by input values Path,ServerRelativeUrl, PageTitle, ZoneId, ZoneIndex.

Please find the sample .DWP file, which you can download and keep inside the Web parts folder.

PS script code-

cls

$0 = $MyInvocation.MyCommand.Definition
$dp0 = [System.IO.Path]::GetDirectoryName($0)
$xmlFilePath = $("$dp0\Inputs.xml")
$xmldata = [xml](Get-Content($xmlFilePath));
$username = "samtest@microsoft.com"
$password = Read-Host -Prompt "Please enter your password" -AsSecureString
$url = $xmldata.WebSite.Url
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
$clientContext = New-Object Microsoft.SharePoint.Client.ClientContext($url)
$credentials = New-ObjectMicrosoft.SharePoint.Client.SharePointOnlineCredentials($username, $securePassword)
$clientContext.Credentials = $credentials

Add-Type -Path "C:\Lib\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Lib\Microsoft.SharePoint.Client.Runtime.dll"
Add-Type -Path "C:\Lib\Microsoft.SharePoint.Client.Publishing.dll"
Add-Type -Path "C:\Lib\Microsoft.SharePoint.Client.Taxonomy.dll"

if (!$clientContext.ServerObjectIsNull.Value)
{
Write-Host "Connected to SharePoint Online site: ‘$Url'" -ForegroundColor Green
$web = $clientContext.Web
$clientContext.Load($web)
$clientContext.ExecuteQuery()
}

function AddWebpart([Microsoft.SharePoint.Client.Web] $web)
{
$pubWeb =[Microsoft.SharePoint.Client.Publishing.PublishingWeb]::GetPublishingWeb($clientContext,$web)
$clientContext.Load($pubWeb)
foreach($webpart in $xmldata.WebSite.Webparts.Webpart)
{
$pagesList = $web.Lists.GetByTitle($webpart.List)
$path=$webpart.Path
$filePath = $("$dp0\$path")
$webpartdata = [xml](Get-Content($filePath));
$wpxml=$webpartdata.OuterXml
$camlQuery = New-Object Microsoft.SharePoint.Client.CamlQuery
$camlQuery.ViewXml = ‘<View><Query><Where><Eq><FieldRef Name="FileLeafRef" /> `
<Value Type="Text">’+$webpart.PageTitle +'</Value></Eq></Where></Query></View>’
$items = $pagesList.GetItems($camlQuery)
$clientContext.Load($items)
$clientContext.ExecuteQuery()
$listItem = $items[0]
$clientContext.Load($listItem)
$clientContext.ExecuteQuery()
$file = $listItem.File
$file.CheckOut()
$clientContext.Load($file)
$clientContext.ExecuteQuery()
$WPManager =$web.GetFileByServerRelativeUrl($webpart.ServerRelativeUrl).GetLimitedWebPartManager("Shared")
$wpd = $WPManager.ImportWebPart($wpxml)
$file =$web.GetFileByServerRelativeUrl($webpart.ServerRelativeUrl).GetLimitedWebPartManager("Shared").AddWebPart($wpd.WebPart,$webpart.ZoneId,$webpart.ZoneIndex)
$listItem.Update()
$listItem.File.CheckIn("", [Microsoft.SharePoint.Client.CheckinType]::MajorCheckIn)
$listItem.File.Publish("")
$clientContext.Load($listItem)
}
}

AddWebpart $web

XML Inputs-

<?xml version="1.0" encoding="utf-8"?>
<WebSite Url="https://microsft.sharepoint.com/sites/test/" >
<Webparts>
<Webpart Path="Webparts\ContentWP.dwp" List="Pages" ServerRelativeUrl="/sites/test/Pages/SamplePage.aspx" PageTitle="SamplePage.aspx" ZoneId="Header" ZoneIndex="1"></Webpart>
</Webparts>

<Folder Path="Pages/Folder1"></Folder>
<Folder Path="Pages/Folder2"></Folder>
<Folder Path="Lists/ImageLibrary/Folder1"></Folder>
</Folders>
</WebSite>

This is how we can add a web part to a web part page programmatically using PowerShell in SharePoint Online/2013/2016.

Create Page Programmatically using CSOM PowerShell in SharePoint 2013/2016

In this post, I will be sharing code to create a page using custom/out of the box page layout using CSOM and PowerShell script in SharePoint 2013/2016.

If you have a requirement to create pages and looking for the automated processes here you go. Find the code below and I hope this will be useful.

Kindly add Page tag entry and specify page name and page layout input in the xml file.

Below is the PowerShell script to create a page programmatically using PowerShell CSOM in SharePoint 2013/2016.

cls

$0 = $MyInvocation.MyCommand.Definition
$dp0 = [System.IO.Path]::GetDirectoryName($0)
$xmlFilePath = $("$dp0\Inputs.xml")
$xmldata = [xml](Get-Content($xmlFilePath));
$username = "samtest@microsoft.com"
$password = Read-Host -Prompt "Please enter your password" -AsSecureString
$url = $xmldata.WebSite.Url
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
$clientContext = New-Object Microsoft.SharePoint.Client.ClientContext($url)
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $securePassword)
$clientContext.Credentials = $credentials

Add-Type -Path "C:\Lib\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Lib\Microsoft.SharePoint.Client.Runtime.dll"
Add-Type -Path "C:\Lib\Microsoft.SharePoint.Client.Publishing.dll"
Add-Type -Path "C:\Lib\Microsoft.SharePoint.Client.Taxonomy.dll"

if (!$clientContext.ServerObjectIsNull.Value)
{
Write-Host "Connected to SharePoint Online site: ‘$Url'" -ForegroundColor Green
$web = $clientContext.Web
$clientContext.Load($web)
$clientContext.ExecuteQuery()
}

function createPages([Microsoft.SharePoint.Client.Web] $web)
{
$rootWeb = $clientContext.Site.RootWeb
$clientContext.Load($rootWeb)
$clientContext.ExecuteQuery()
foreach($page in $xmldata.WebSite.Pages.Page)
{
$mpList = $rootWeb.Lists.GetByTitle(‘Master Page Gallery’)
$camlQuery = New-Object Microsoft.SharePoint.Client.CamlQuery
$camlQuery.ViewXml = ‘<View><Query><Where><Eq><FieldRef Name="FileLeafRef" /> `
<Value Type="Text">’+$page.Layout+'</Value></Eq></Where></Query></View>’
$items = $mpList.GetItems($camlQuery)
$clientContext.Load($items)
$clientContext.ExecuteQuery()
$articleLayoutItem = $items[0]
$clientContext.Load($articleLayoutItem)
$clientContext.ExecuteQuery()

$pubWeb = [Microsoft.SharePoint.Client.Publishing.PublishingWeb]::GetPublishingWeb($clientContext, $web)
$clientContext.Load($pubWeb)
$pagesList = $web.Lists.GetByTitle(‘Pages’)
$title =$page.Name
$pubPageInfo = New-Object Microsoft.SharePoint.Client.Publishing.PublishingPageInformation
$pubPageInfo.Name = $title.Replace(" ", "-") + ".aspx"
$pubPageInfo.PageLayoutListItem = $articleLayoutItem
$pubPage = $pubWeb.AddPublishingpage($pubPageInfo)
$pubPage.ListItem.File.CheckIn("", [Microsoft.SharePoint.Client.CheckinType]::MajorCheckIn)
$pubPage.ListItem.File.Publish("")

$clientContext.Load($pubPage)
$clientContext.ExecuteQuery()
Write-Host "Page Ceated: ‘$title'" -ForegroundColor Green

$listItem = $pubPage.get_listItem()
$clientContext.Load($listItem)
$clientContext.ExecuteQuery()

$file = $listItem.File
$file.CheckOut()
$clientContext.Load($file)
$clientContext.ExecuteQuery()

$listItem.Set_Item("Title", $title)

$listItem.Update()
$listItem.File.CheckIn("", [Microsoft.SharePoint.Client.CheckinType]::MajorCheckIn)
$listItem.File.Publish("")
$clientContext.Load($listItem)
$clientContext.ExecuteQuery()
}

}
createPages $web

XML Inputs-

<?xml version="1.0″ encoding="utf-8″?>
<WebSite Url="https://microsft.sharepoint.com/sites/test/" >
<Pages>
<Page Name="HomePage" Layout="CustomLayout.aspx" />
<Page Name="Page1″ Layout="BlankWebPartPage.aspx"/>
<Page Name="Page2″ Layout="BlankWebPartPage.aspx"/>
</Pages>
</WebSite>

This is how we can create a web part page in SharePoint Online using PowerShell.

Get user profile properties using PowerShell in SharePoint 2013/2016

Now, we will see how to get user profile properties in SharePoint 2013/2016 using PowerShell. The PowerShell script, you can write, test and debug using Windows PowerShell ISE or by using Visual Studio code.

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
$siteUrl = "http://****.****.com/"
$outputFile = $("$dp0\UserInfo.csv")
$serviceContext = Get-SPServiceContext -Site $siteUrl
$profileManager = New-Object Microsoft.Office.Server.UserProfiles.UserProfileManager($serviceContext);
$profiles = $profileManager.GetEnumerator()
$collection = @()
foreach ($profile in $profiles) {
$profileData = "" |
select "AccountName", "PreferredName"
#$ADUser = Get-ADUser -Filter {SamAccountName -eq $profile.Name}
$profileData.AccountName = $profile["AccountName"]
$profileData.PreferredName = $profile["PreferredName"]
#$collection += $profileData | ConvertTo-Html -Fragment
$collection += $profileData
}
$collection | Export-Csv $outputFile -NoTypeInformation

This is how we can get user profile properties like accountname, preferred name, etc using PowerShell in SharePoint.

Get Size of subsites using PowerShell in SharePoint 2016/2013/2010

We were having a requirement to get each site collection and subsites size throughout the web application in SharePoint 2013/2016/2010.

Below PowerShell script can be used to get the size of sites and subsites in SharePoint.

Create sitesInputs.csv file to keep site URL and Siteize.csv to keep the site size details.

You can place PS file and CSV files inside one folder.

cls
#———————————–
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint") > $null

$LogDir = $("$dp0\")

#The datatable which contains all the User information
$CSVDtTb = New-Object system.Data.DataTable "tabName"
$isLogFileCreated = $False

Function CreateCSVDtTb()
{

if(!$isLogFileCreated){
#Define Columns

$dcObjUrl = New-Object system.Data.DataColumn SiteUrl,([string])
$dcSizeinMB = New-Object system.Data.DataColumn SizeinMB,([string])
$dcSizeinGB = New-Object system.Data.DataColumn SizeinGB,([string])

#Add the Columns
$CSVDtTb.columns.add($dcObjUrl)
$CSVDtTb.columns.add($dcSizeinMB)
$CSVDtTb.columns.add($dcSizeinGB)
$script:isLogFileCreated = $True
}
}

Function AddRow([string] $SiteUrl,[string] $SizeinMB,[string] $SizeinGB )
{
#Create a row
$row = $CSVDtTb.NewRow()

#Enter data in the row
$row.SiteUrl = $SiteUrl
$row.SizeinMB = $SizeinMB
$row.SizeinGB = $SizeinGB

#Add the row to the table
$CSVDtTb.Rows.Add($row)
}

function GetWebSize ($Web)
{
[long]$subtotal = 0
foreach ($folder in $Web.Folders)
{
$subtotal += GetFolderSize -Folder $folder
}
write-host "Site" $Web.Title "is" $subtotal "KB"
return $subtotal
}
# loop through all the subsites until nth level
function GetSubWebSizes ($Web)
{
[long]$subtotal = 0
foreach ($subweb in $Web.Webs)
{
[long]$webtotal = 0
foreach ($folder in $subweb.Folders)
{
$webtotal += GetFolderSize -Folder $folder
}
$subtotal += $webtotal
$subtotal += GetSubWebSizes -Web $subweb
}
return $subtotal
}
# loop through all the folder level
function GetFolderSize ($Folder)
{
[long]$folderSize = 0
foreach ($file in $Folder.Files)
{
$folderSize += $file.Length;
}
foreach ($fd in $Folder.SubFolders)
{
$folderSize += GetFolderSize -Folder $fd
}
return $folderSize
}
Function GenerateSiteInfo($TargetSiteUrl)
{

#Start Script Execution

CreateCSVDtTb

#Create a variable based on the current date and time
$StartTime = (Get-Date -UFormat "%Y-%m-%d_%I-%M-%S %p").tostring()
$CsvReportFile = "$LogDir\Siteize.csv"
Write-Host "Start Processing…"

#Get all sites within each of the specified web application
$site = new-Object Microsoft.SharePoint.SPSite($TargetSiteUrl)
$TargetWeb = $site.OpenWeb()
[long]$total = 0
$total += GetWebSize -Web $TargetWeb
$total += GetSubWebSizes -Web $TargetWeb
$totalInMb = ($total/1024)/1024
$totalInMb = "{0:N2}" -f $totalInMb
$totalInGb = (($total/1024)/1024)/1024
$totalInGb = "{0:N2}" -f $totalInGb
#write-host "Total size of all sites below" $StartWeb "is" $total "Bytes,"
write-host "which is" $totalInMb "MB or" $totalInGb "GB"
AddRow -SiteUrl $row.SiteUrl -SizeinMB $totalInMb -SizeinGB $totalInGb
$site.Dispose()
$CSVDtTb | Export-Csv $CsvReportFile -NoTypeInformation
Write-Host "End Processing…"
}

#——————————————–

function GetAllSites ($CsvFilePath)
{
write-host "Process Started …."
$CSVData = Import-CSV -Path $CsvFilePath
#loop through all the siteURLS in CSV file
foreach($row in $CSVData)
{
try
{
write-host "Fetching the Site Size : " $row.SiteUrl;
GenerateSiteInfo($row.SiteUrl)
}
catch
{
write-host $row.SiteUrl "does not exist…" +$_.Exception.Message -BackgroundColor DarkGray
}
}
write-host "Process Ended …."
}
GetAllSites($LogDir+"\sitesInputs.csv")

This is how we can size of subsites using PowerShell in SharePoint 2016/2013 or SharePoint 2010.

Create SharePoint 2013 site collection group using PowerShell

Now, I will be sharing PowerShell script to create groups in SharePoint Site collection. The PowerShell script is applicable to both SharePoint 2013/2016 and SharePoint 2010.

Kindly create SiteCollectionGroups.CSV file and add below columns to keep input values.

  • SiteCollectionURL
  • GroupName

The file will look like the below image.

create sharepoint site collection group using powershell

Below is the PowerShell Script Code to create a SharePoint site collection group using PowerShell.

$0 = $MyInvocation.MyCommand.Definition
$dp0 = [System.IO.Path]::GetDirectoryName($0)
$path = $(“$dp0\SiteCollectionGroups.csv”)
$csv = Import-csv -path $path

foreach($line in $csv)
{
$siteCollURL = $line.SiteCollectionURL
$groupName = $line.GroupName
write-host $siteCollURL “….” $groupName
Add-PSSnapin microsoft.sharepoint.powershell -ErrorAction SilentlyContinue
[System.Reflection.Assembly]::LoadWithPartialName(“Microsoft.SharePoint”) | Out-null

$site = New-Object Microsoft.SharePoint.SPSite($siteCollURL)
$web = $site.RootWeb;
$exists = $web.SiteGroups | where { $_.Name -eq $groupName }
if ($exists -eq $null)
{
$web.SiteGroups.Add($groupName,$web.CurrentUser,$web.CurrentUser,$groupName)
Write-Host $groupName ” is created in ” $siteCollURL “….”
}
$web.Close
$site.Close
}

This is how we can create groups using PowerShell in SharePoint 2013/2016.

Assign permission level to SharePoint 2013 groups using PowerShell

Now, we will see how to assign permission levels to SharePoint 2013 groups using PowerShell.

Below I will be sharing code to provide security permission to different SharePoint Groups. The code is applicable for SharePoint 2010 and SharePoint 2013/2016.

Create a CSV file named ChangeGroupPermAtWebLevel.CSV and add below columns.

  • WebURL
  • WebHasUniquePermission
  • GroupName
  • ChangeToPermissionLevel

You can provide any name to CSV but change the file name details in the PS script code.

assign permission level to SharePoint 2013 groups using PowerShell

Below is the PowerShell Script to assign a permission level to SharePoint 2013 groups using PowerShell.

$0 = $MyInvocation.MyCommand.Definition
$dp0 = [System.IO.Path]::GetDirectoryName($0)
$path = $("$dp0\ChangeGroupPermAtWebLevel.csv")
$csv = Import-csv -path $path

foreach($line in $csv)
{
$siteURL = $line.WebURL
$groupName = $line.GroupName
$PermLevel = $line.ChangeToPermissionLevel
$CurrentPermLevels = $line.GroupPermission

write-host $siteURL "…." $groupName "……" $PermLevel

if ( (Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null )
{
Add-PSSnapin Microsoft.SharePoint.PowerShell
}

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint") | Out-null

$web = Get-SPWeb $siteURL

if ($web.HasUniquePerm -eq $true)
{
$group = $web.SiteGroups[$groupName]
if($group.Roles.Count -eq "0")
{
$assign = New-Object Microsoft.SharePoint.SPRoleAssignment($group);
#$objDefination=$web.RoleDefinitions.GetByName($PermLevel);
$assign.RoleDefinitionBindings.Add($web.RoleDefinitions[$PermLevel])
$web.RoleAssignments.Add($assign);
$web.Properties.Update()
}
else
{
$assign = $web.RoleAssignments.GetAssignmentByPrincipal($group);

for ($i = $assign.RoleDefinitionBindings.Count – 1; $i -ge 0; $i–-)
{
$assign.RoleDefinitionBindings.Remove($i)
$assign.Update()
}
$assign.Update()
$assign.RoleDefinitionBindings.Add($web.RoleDefinitions[$PermLevel])
$assign.Update()
}
Write-Host $PermLevel "Permission Level Assigned…."
}
$web.Dispose
}

This is how we can assign a permission level to SharePoint 2013 groups using PowerShell.

You may like following PowerShell SharePoint tutorials:

This PowerShell SharePoint tutorial, we saw various PowerShell examples to work with SharePoint site, list, library, content types, etc in SharePoint Online or SharePoint 2013/2016.

Donwload Hub site pdf

Download SharePoint Online Tutorial PDF FREE!

Get update on Webinars, video tutorials, training courses etc.

Sambita Rath

I have 9 years of exprience into SharePoint implementation, architecture, Administrator, development and Training.Designing Information Architecture in SharePoint 2007, 2010,2013 and Office 365.

>