Skip to content

Collection of #Powershell Scripts for Sharepoint #ContentType #CTHub #Sites #Lists

In my current client project I had to design a Sharepoint portal with many lists and libraries that will eventually be re-usable across the organisation (ie the same lists structure will be used by several sites, sub-sites under several site collections and potentially in separate web applications), therefore using the SharePoint Content Type Hub was the obvious built-in solution to keep the Content Types centrally managed. However you will find out that using the browser to perform the tasks to edit the content types and publish them to all sites can become a major time consuming and if like me you don’t like to click twice to achieve the same thing, the need to automate those edits is paramount. Powershell to the rescue, here are the main scripts I use for manipulating Content Types, pushing them, but also others such as create new web application, new site collection, managed path, content type and more.

(click each “expand source” section to grab the scripts)
  • Add Sharepoint Snap-In to Powershell
(the basis if using PowerGui, which I definitely recommend, thanks Paul  for recommending it to me, this tool totally changed my opinion on Powershell)

[sourcecode language=”powershell” collapse=”true” autolinks=”false”]
Add-PsSnapin Microsoft.SharePoint.PowerShell
[System.Reflection.Assembly]::LoadWithPartialName(‘Microsoft.SharePoint’)
[/sourcecode]

  • Activate Taxonomy feature option under Site Collection Administration
 (to receive Content Type Hub Published content types, missing from Blank Template)

[sourcecode language=”powershell” collapse=”true” autolinks=”false”]
# Activate Content TypeHub option under Site Collection Administration
stsadm -o activatefeature -id 73EF14B1-13A9-416b-A9B5-ECECA2B0604C -url http://MySharePointSrv.com/sites/sitecol1
[/sourcecode]

  • Unpublish All Content Types containing Custom Group Name

[sourcecode language=”powershell” collapse=”true” autolinks=”false”]
$HubUrl = “http://cthub.MySharePointSrv.com”
$HubSite = Get-SPSite $HubUrl
$HubWeb = $HubSite.RootWeb
$Publisher = New-Object Microsoft.SharePoint.Taxonomy.ContentTypeSync.ContentTypePublisher($HubSite)
$ContentTypes = $HubWeb.ContentTypes
foreach ($ContentType in $ContentTypes)
{
$contentTypeGroup = $ContentType.Group
$contentTypeName = $ContentType.Name
# only publish the nMySharePointSrv Conten Types
if ( $contentTypeGroup -like ‘*MyCustomGroupName*’)
{
$Publisher.Unpublish($ContentType)
echo “UNPUBLISHED [CONTENT TYPE GROUP] $contentTypeGroup, $contentTypeName”
}
}
$HubSite.Dispose()
[/sourcecode]

  • (re)Publish All Content Types containing Custom Group Name to Subscribing web application

[sourcecode language=”powershell” collapse=”true” autolinks=”false”]
$HubUrl = “http://cthub.MySharePointSrv.com”
$HubSite = Get-SPSite $HubUrl
$HubWeb = $HubSite.RootWeb
$Publisher = New-Object Microsoft.SharePoint.Taxonomy.ContentTypeSync.ContentTypePublisher($HubSite)
$ContentTypes = $HubWeb.ContentTypes
foreach ($ContentType in $ContentTypes)
{
$contentTypeGroup = $ContentType.Group
$contentTypeName = $ContentType.Name
# only publish the nMySharePointSrv Conten Types
if ( $contentTypeGroup -like ‘*MyCustomGroupName*’)
{
$Publisher.Publish($ContentType)
echo “PUBLISHED [CONTENT TYPE GROUP] $contentTypeGroup, $contentTypeName”
}
}
$HubSite.Dispose()
[/sourcecode]

  • Force the Publish content types from Content Type Hub to a target web application (instead of waiting for job to start on schedule

[sourcecode language=”powershell” collapse=”true” autolinks=”false”]
# http://get-spscripts.com
#Run the Content Type Hub timer job
$ctHubTJ = Get-SPTimerJob “MetadataHubTimerJob”
$ctHubTJ.RunNow()
#Run the Content Type Subscriber timer job for a specific Web Application
$ctSubTJ = Get-SPTimerJob “MetadataSubscriberTimerJob” -WebApplication http://MySharePointSrv.com
$ctSubTJ.RunNow()
echo “Metadata Hub Job initiated”
[/sourcecode]

  • Read a text file that lists some files to be used as Content Types, iterates through each files and its create contents

The IMPORTFILES.TXT has this format

doc1 – Document title1.dotx
doc2 – Document title2.dotx
doc3 – Document title3.dotx

[sourcecode language=”powershell” collapse=”true” autolinks=”false”]
# Set Variables
$url = “http://cthub.MySharePointSrv.com”
$cGroup = “MyContentTypes Group”
# Read list of document template to create CT
$DocumentTemplatesArray = Get-Content “C:\temp\IMPORTFILES.txt”
$CTHubSiteColl = “http://cthub.MySharePointSrv.com”
$site = get-spsite $url
$web = $site.openweb()
$ctypeParent = $web.availablecontenttypes[“Document”]
# Loop thru the number of CT to create
$i = 0
$MaxCT = $DocumentTemplatesArray.count # total CT to create
write-host “——–” + $DocumentTemplatesArray.count total lines read from file + “——-“+
foreach ($line in $DocumentTemplatesArray)
{
$templateURL = “/DocumentTemplates/” + $ctypeName # URL of templatefile with extension
$ctypeName = $line.replace(“.doc”,””).replace(“.xls”,””).replace(“.vst”,””).replace(“.xltx”,””) #name of CT without extension
Write-Host $i + “: ” + $ctypeName
$ctype = new-object Microsoft.SharePoint.SPContentType($ctypeParent, $web.contenttypes, $ctypeName)
$web.contenttypes.add($ctype)
# ADD CUSTOM COLUMN
$web.fields.add(“myField”, ([Type]“Microsoft.SharePoint.SPFieldType”)::Text, $false)
$field = $web.fields.getfield(“myField”)
$fieldLink = new-object Microsoft.SharePoint.SPFieldLink($field)
$ctype.fieldlinks.add($fieldLink)
# set the current document template file to be the document tmeplate
$ctype.DocumentTemplate = $templateURL
$ctype.Group = $cGroup # give GroupName
#
write-Host “—- now publish to : ” + $CTHubSiteColl
$Publisher = New-Object Microsoft.SharePoint.Taxonomy.ContentTypeSync.ContentTypePublisher($CTHubSiteColl)
$Publisher.Publish($ctype);
# update the content type
$ctype.Update()
$i++
}
# END OF LOOP TO CREATE CT
$web.Dispose()
$site.Dispose()
[/sourcecode]

  • Create a new Web Application

[sourcecode language=”powershell” collapse=”true” autolinks=”false”]
# Declare Variables
$siteName = “SP – MyWebApp.sharepoint.com”
$port = 80
$hostHeader = “MyWebApp.sharepoint.com”
$path = “d:\dedicateddrive\MyWebApp.sharepoint.com”
$url = “http://MyWebApp.sharepoint.com:80”
$appPoolName = “SP – MyWebApp.sharepoint.com”
$managedAccount = “sharepoint\Sharepoint-WebApp-MA”
$dbServer = “Sharepoint-SQL”
$dbName = “Sharepoint-MyWebApp”
$allowAnonymous = $false
$authenticationMethod = “NTLM”
$ssl = $false
#Create the Web app
New-SPWebApplication -Name $siteName -Port $port -HostHeader $hostHeader -Path $Path -URL $url -ApplicationPool $appPoolName -ApplicationPoolAccount (Get-SPManagedAccount “$managedAccount”) -DatabaseName $dbName -DatabaseServer $dbServer -AllowAnonymousAccess: $allowAnonymous -AuthenticationMethod $authenticationMethod -SecureSocketsLayer:$ssl

[/sourcecode]

  • Convert existing Web Application from classic-mode to claims-based authentication 

[sourcecode language=”powershell” collapse=”true” autolinks=”false”]
# http://technet.microsoft.com/en-us/library/gg251985(v=office.14).aspx
#set the specified user account as an administrator for the site
$WebAppName = “http://MySharePointSrv.com”
$wa = get-SPWebApplication $WebAppName
$wa.UseClaimsAuthentication = $true
$wa.Update()
#configure the policy to enable the user to have full access
$account = “MySharePointSrv\SPSetup”
$account = (New-SPClaimsPrincipal -identity $account -identitytype 1).ToEncodedString()
$wa = get-SPWebApplication $WebAppName
$zp = $wa.ZonePolicies(“Default”)
$p = $zp.Add($account,”PSPolicy”)
$fc=$wa.PolicyRoles.GetSpecialRole(“FullControl”)
$p.PolicyRoleBindings.Add($fc)
$wa.Update()
#Migrate users
$wa.MigrateUsers($true)
$wa.ProvisionGlobally()
[/sourcecode]

  • Create a new Managed Path

[sourcecode language=”powershell” collapse=”true” autolinks=”false”]
$ManagedPath = “/teams”
$WebApplication= “http://MySharePointSrv.com”
New-SPManagedPath -RelativeURL $ManagedPath -WebApplication $WebApplication
[/sourcecode]

  • Create a new Site Collection

[sourcecode language=”powershell” collapse=”true” autolinks=”false”]
# —- CONFIGURATION BLOCK —-
$WebApplication= “http://MySharePointSrv.com”
$url = “http://MySharePointSrv.com”
$ContentDatabase = “SP-ContentDB1”
$WebsiteName = “MyNewWebApp”
$WebsiteDesc = “”
$Template = “STS#1”
# STS#0 Team site
# STS#1 Blank site
# enter the command GET-SPWebTemplate to choose different template
# the username, display name, and email address
$PrimaryLogin = “MySharePointSrv\SPSetup”
$PrimaryDisplay = “SPSetup”
$PrimaryEmail = “[email protected]
# Information about the secondary site collection administrator (Secondary Owner)
$SecondaryLogin = “MySharePointSrv\SPAdmin”
$SecondaryDisplay = “SPAdmin”
$SecondaryEmail = “[email protected]
# Names of the default Members and Viewers groups
$MembersGroup = “$WebsiteName Members”
$ViewersGroup = “Viewers”
# —- END OF VARIABLES —-
# You should not have to change any of the remaining code
# Unless you want to change the functionality of the script itself
# Create New Managed Path /
# New-SPManagedPath -RelativeURL “/site1” -WebApplication $WebApplication
Write-Host “Creating ContentDatabase “$ContentDatabase “……”
# Create new Content DB
New-SPContentDatabase -Name $ContentDatabase -WebApplication $WebApplication
Write-Host “Creating SiteCollection “$url”……”
# Create New Site Collection in same Content Database
New-SPSite -Url $url –ContentDatabase $ContentDatabase -Name $WebsiteName –Description $WebsiteDesc -Template $Template -OwnerAlias $PrimaryLogin –OwnerEmail $PrimaryEmail -SecondaryOwnerAlias $SecondaryLogin -SecondaryEmail $SecondaryEmail
# default groups (Visitor, Members, and Owners)
$web = Get-SPWeb $url
$web.CreateDefaultAssociatedGroups($PrimaryLogin,$SecondaryLogin,””)
$PrimaryAdmin = Get-SPUser $PrimaryLogin -Web $url
$PrimaryAdmin.Name = $PrimaryDisplay
$PrimaryAdmin.Update()
$SecondaryAdmin = Get-SPUser $SecondaryLogin -Web $url
$SecondaryAdmin.Name = $SecondaryDisplay
$SecondaryAdmin.Update()
# Finish by disposing of the SPWeb object to be a good PowerShell citizen
$web.Dispose()
[/sourcecode]

  • Create a Sites and Sub-sites from an XML file

source: http://geekswithblogs.net/Norgean/archive/2012/04/12/creating-sharepoint-sites-from-xml-using-powershell.aspx Create the structure in websites.XML:

[sourcecode language=”xml” collapse=”true” autolinks=”false”]
[/sourcecode]

Read this structure in Powershell, and recursively create the sites. with a progress dialog barre, too. (enter the command GET-SPWebTemplate to choose different template)
[sourcecode language=”powershell” collapse=”true” autolinks=”false”]
$url = “http://MySharePointSrv.com”
$PathFile = “C:\Powershell\websites.xml”
$SiteTemplate = “BLANKINTERNET#2”
$snap = Get-PSSnapin | Where-Object { $_.Name -eq “Microsoft.SharePoint.Powershell” }
if ($snap -eq $null)
{
Add-PSSnapin “Microsoft.SharePoint.Powershell”
}
function CreateSites($baseUrl, $sites, [int]$progressid)
{
$sitecount = $sites.ChildNodes.Count
$counter = 0
foreach ($site in $sites.Site)
{
Write-Progress -ID $progressid -Activity “Creating sites” -status “Creating $($site.Name)” -percentComplete ($counter / $sitecount*100)
$counter = $counter + 1
Write-Host “Creating $($site.Name) $($baseUrl)/$($site.Url)”
New-SPWeb -Url “$($baseUrl)/$($site.Url)” -AddToQuickLaunch:$false -AddToTopNav:$true -Confirm:$false -Name “$($site.Name)” -Template “$SiteTemplate” -UseParentTopNav:$true
if ($site.ChildNodes.Count -gt 0)
{
CreateSites “$($baseUrl)/$($site.Url)” $site ($progressid +1)
}
Write-Progress -ID $progressid -Activity “Creating sites” -status “Creating $($site.Name)” -Completed
}
}
# read an xml file
$xml = [xml](Get-Content $PathFile)
$xml.PreserveWhitespace = $false
CreateSites $url $xml.Sites 1

[/sourcecode]
  • Delete sites listed in XML file
source: http://geekswithblogs.net/Norgean/archive/2012/04/12/creating-sharepoint-sites-from-xml-using-powershell.aspx Create the structure in websites.XML:
[sourcecode language="xml" collapse="true" autolinks="false"]
[/sourcecode]

Read this structure in Powershell, and recursively delete the sites. this time from the latest down the hierarchy and up .  
[sourcecode language="powershell" collapse="true" autolinks="false"]
$url = "http://MySharePointSrv.com"
$PathFile = "C:\Powershell\websites.xml"
$url = "http://dev.company.com"
$PathFile = "C:\CPS\Powershell\websites.xml"
$snap = Get-PSSnapin | Where-Object { $_.Name -eq "Microsoft.SharePoint.Powershell" }
if ($snap -eq $null)
{
Add-PSSnapin "Microsoft.SharePoint.Powershell"
}
function DeleteSites($baseUrl, $sites, [int]$progressid)
{
$sitecount = $sites.ChildNodes.Count
$counter = 0
foreach ($site in $sites.Site)
{
Write-Progress -ID $progressid -Activity "Deleting sites" -status "Deleting $($site.Name)" -percentComplete ($counter / $sitecount*100)
$counter = $counter + 1
if ($site.ChildNodes.Count -gt 0)
{
DeleteSites "$($baseUrl)/$($site.Url)" $site ($progressid +1)
}
Write-Host "Deleting $($site.Name) $($baseUrl)/$($site.Url)"
$WebSiteIdentity = "$($baseUrl)/$($site.Url)"
  Remove-SPWeb -Identity $WebSiteIdentity
Write-Progress -ID $progressid -Activity "Deleting sites" -status "Deleting $($site.Name)" -Completed
}
}
# read an xml file
$xml = [xml](Get-Content  $PathFile)
$xml.PreserveWhitespace = $false
DeleteSites $url $xml.Sites 1
[/sourcecode]

  • Change a site collection Master Page to a Custom.master
[sourcecode language="powershell" collapse="true" autolinks="false"]
$url = "http://MySharePointSrv.com"
$Scollection = ""
$NewMasterPage = "$Scollection/_catalogs/masterpage/Custom.master"
$web = Get-SPWeb $url
Write-Host $NewMasterPage
$web.CustomMasterUrl = $NewMasterPage
$web.MasterUrl = $NewMasterPage
$web.Update()
Write-Host "...done."
$url = "http://MySharePointSrv.com/sites/sitecol1/site1"
$Scollection = "/sites/sitecol1"
$NewMasterPage = "$Scollection/_catalogs/masterpage/custom.master"
$web = Get-SPWeb $url
Write-Host $NewMasterPage
$web.CustomMasterUrl = $NewMasterPage
$web.MasterUrl = $NewMasterPage
$web.Update()
Write-Host "...done."
$url = "http://MySharePointSrv.com/teams/IT"
$Scollection = "/teams/IT"
$NewMasterPage = "$Scollection/_catalogs/masterpage/custom.master"
$web = Get-SPWeb $url
Write-Host $NewMasterPage
$web.CustomMasterUrl = $NewMasterPage
$web.MasterUrl = $NewMasterPage
$web.Update()
Write-Host "...done."
$url = "http://MySharePointSrv.com/sites/sitecol1"
$Scollection = "/sites/sitecol1"
$NewMasterPage = "$Scollection/_catalogs/masterpage/custom.master"
$web = Get-SPWeb $url
Write-Host $NewMasterPage
$web.CustomMasterUrl = $NewMasterPage
$web.MasterUrl = $NewMasterPage
$web.Update()
Write-Host "...done."
$url = "http://MySharePointSrv.com/sites/sitecol1/template"
$Scollection = "/sites/sitecol1"
$NewMasterPage = "$Scollection/_catalogs/masterpage/custom.master"
$web = Get-SPWeb $url
Write-Host $NewMasterPage
$web.CustomMasterUrl = $NewMasterPage
$web.MasterUrl = $NewMasterPage
$web.Update()
Write-Host "...done."
[/sourcecode]
  • Remove site columns
[sourcecode language="powershell" collapse="true" autolinks="false"]
# Set Variables
$url = "http://cthub.MySharePointSrv.com"
$siteColumnsList = "myField" # Specify a list of Site Column Names to be deleted, seperated by ;
$site = new-object Microsoft.SharePoint.SPSite($url)
$array = $siteColumnsList.Split(";")
$site = get-spsite $url
$web = $site.openweb()
# go thru each content type to remove column
foreach ($ctype in $web.ContentTypes)
{
foreach($colms in $array)
{
try
{
#Get link to the columnn from the web
$spFieldLink = New-Object Microsoft.SharePoint.SPFieldLink ($web.Fields[$colms])
#Remove the column from the content type and update
$ct.FieldLinks.Delete($spFieldLink.Id)
$ct.Update()
# below 2 lines is to delete from Site, when not in a ContentType
# $column = $site.rootweb.Fields[$colms]
# $site.rootweb.Fields.Delete($column)
Write-Host $column.Title "deleted successfully."
}
catch [System.Exception]
{
Write-Host $column.Title "deleted failed."
#Best Attempt to Remove Site Columns
}
}
}
$site.Dispose()
[/sourcecode]