SharePoint change document set and items content type to a new content type

I’ll put it simply:

This is a PowerShell script that you can use to change a content type of a library or list to another one. This script can identify between Document Sets and library or list items.


param (
[string]$WebsiteUrl = "http://portal.spdev.com/",
[string]$OldCTName = "DSTestCT",
[string]$NewCTName = "DSTestCT"
)

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

function Reset-ListContentType ($WebUrl, $ListName, $OldCTName, $NewCTName)
{
$web = $null
try
{
$web = Get-SPWeb $WebUrl

$list = $web.Lists.TryGetList($ListName)
$oldCT = $list.ContentTypes[$OldCTName]

$isChildOfCT = $list.ContentTypes.BestMatch($rootNewCT.ID).IsChildOf($rootNewCT.ID);
if($oldCT -ne $null -and $isChildOfCT -eq $false)
{
$hasOldCT = $true
$isFoldersCTReseted = Reset-SPFolderContentType –web $web -list $list –OldCTName $OldCTName –NewCTName $NewCTName
Reset-SPFileContentType –web $web -list $list –OldCTName $OldCTName –NewCTName $NewCTName
Remove-ListContentType –web $web -list $list –OldCTName $OldCTName –NewCTName $NewCTName
if($hasOldCT -eq $true)
{
Add-ListContentType –web $web -list $list –OldCTName $OldCTName –NewCTName $NewCTName
if($isFoldersCTReseted -eq $true)
{
Set-SPFolderContentType –web $web -list $list –OldCTName $OldCTName –NewCTName $NewCTName
}
}
}


}catch
{

}
finally
{
if($web)
{
$web.Dispose()
}
}

}

function Remove-ListContentType ($web, $list, $OldCTName, $NewCTName)
{


$oldCT = $list.ContentTypes[$OldCTName]

$isChildOfCT = $list.ContentTypes.BestMatch($oldCT.ID).IsChildOf($oldCT.ID);

if($isChildOfCT -eq $true)
{
$list.ContentTypes.Delete($oldCT.ID)
}
$web.Dispose()

return $isChildOfCT
}

function Add-ListContentType ($web, $list, $OldCTName, $NewCTName)
{



$list.ContentTypes.Add($rootNewCT)

$web.Dispose()
}

function Reset-SPFolderContentType ($web, $list, $OldCTName, $NewCTName)
{
#Get web, list and content type objects

$isFoldersCTReseted = $false


$isChildOfCT = $list.ContentTypes.BestMatch($rootNewCT.ID).IsChildOf($rootNewCT.ID);

$oldCT = $list.ContentTypes[$OldCTName]
$folderCT = $list.ContentTypes["Folder"]
$newCT = $rootNewCT

$newCTID = $newCT.ID

#Check if the values specified for the content types actually exist on the list
if (($oldCT -ne $null) -and ($newCT -ne $null))
{
$list.Folders | ForEach-Object {

if ($_.ContentType.ID.IsChildOf($rootNewCT.ID) -eq $false -and $_.ContentType.ID.IsChildOf($oldCT.ID) -eq $true -and $_.Folder.ProgID -eq "Sharepoint.DocumentSet")
{
Write-Host "Found a document set: " $_.Name "Processing document set"
$item = $list.GetItemById($_.ID);
$item["ContentTypeId"] = $folderCT.Id
$item.Update()
$isFoldersCTReseted = $true
}
}
}

$web.Dispose()

return $isFoldersCTReseted
}

function Set-SPFolderContentType ($web, $list, $OldCTName, $NewCTName)
{
#Get web, list and content type objects



$folderCT = $list.ContentTypes["Folder"]
$newCT = $list.ContentTypes[$NewCTName]

#Check if the values specified for the content types actually exist on the list
if (($newCT -ne $null))
{
$list.Folders | ForEach-Object {
if ($_.ContentType.ID.IsChildOf($newCT.ID) -eq $false -and $_.ContentType.ID.IsChildOf($folderCT.ID) -eq $true -and $_.Folder.ProgID -eq "Sharepoint.DocumentSet")
{
$item = $list.GetItemById($_.ID);
$item["ContentTypeId"] = $newCT.Id
$item.Update()
}
}
}

$web.Dispose()
}


function Reset-SPFileContentType ($web, $list, $OldCTName, $NewCTName)
{
#Get web, list and content type objects



$isChildOfCT = $list.ContentTypes.BestMatch($rootNewCT.ID).IsChildOf($rootNewCT.ID);

$oldCT = $list.ContentTypes[$OldCTName]
$folderCT = $list.ContentTypes["Folder"]
$newCT = $rootNewCT

$newCTID = $newCT.ID

#Check if the values specified for the content types actually exist on the list
if (($oldCT -ne $null) -and ($newCT -ne $null))
{
$list.Folders | ForEach-Object {
if ($_.ContentType.ID.IsChildOf($rootNewCT.ID) -eq $false -and $_.ContentType.ID.IsChildOf($oldCT.ID) -eq $true)
{
$_["ContentTypeId"] = $folderCT.Id
$_.Update()
}
}
#Go through each item in the list
$list.Items | ForEach-Object {
Write-Host "Item present CT ID :" $_.ContentType.ID
Write-Host "CT ID To change from :" $oldCT.ID
Write-Host "NEW CT ID to change to:" $rootNewCT.ID

#Check if the item content type currently equals the old content type specified
if ($_.ContentType.ID.IsChildOf($rootNewCT.ID) -eq $false -and $_.ContentType.ID.IsChildOf($oldCT.ID) -eq $true)
{
#Check the check out status of the file
if ($_.File.CheckOutType -eq "None")
{
Change the content type association for the item
$item = $list.GetItemById($_.ID);
$item.File.CheckOut()
write-host "Resetting content type for file: " $_.Name "from: " $oldCT.Name "to: " $newCT.Name

$item["ContentTypeId"] = $newCTID
$item.UpdateOverwriteVersion()
Write-Host "Item changed CT ID :" $item.ContentType.ID
$item.File.CheckIn("Content type changed to " + $newCT.Name, 1)
}
else
{
write-host "File" $_.Name "is checked out to" $_.File.CheckedOutByUser.ToString() "and cannot be modified"
}
}
else
{
write-host "File" $_.Name "is associated with the content type" $_.ContentType.Name "and shall not be modified"
}
}
}
else
{
write-host "One of the content types specified has not been attached to the list"$list.Title
return
}

$web.Dispose()
}

$web = Get-SPWeb $WebsiteUrl
$rootWeb = $web.Site.RootWeb;
$rootNewCT = $rootWeb.AvailableContentTypes[$NewCTName]

Foreach ($list in $web.Lists) {
Write-Host $list.BaseType
if($list.Hidden -eq $false -and $list.BaseType -eq "DocumentLibrary")
{
Write-Host "Processing list: " $list.Title
Reset-ListContentType –WebUrl $WebsiteUrl –ListName $list.Title –OldCTName $OldCTName –NewCTName $NewCTName
}
}

$web.Dispose()

 

Tutorial guide: Learn Python basics

Hi ok, here are my own notes on the basics of Python. I am working on a Udemy course on data science and got excited about Python(it has been while since I’ve done something cool with Python, so I am excited 🙂 ). This is based on the Udemy course https://www.udemy.com/data-science-and-machine-learning-with-python-hands-on

Where it goes, hope it helps.

You can run python code as scripts or as a python notebook.

 

Running a script from a command prompt:

python “your script file location and name”

 

Basic basics

 

List definition:

listOfNumbers = [1, 2, 3, 4, 5, 6]

 

Iteration through a list of items:

for number in listOfNumbers:

print number,

if (number % 2 == 0):

print “is even”

else:

print “is odd”

 

#Notice: In python you differentiate between blocks of code by whitespace, or a tab. Not the same as let say Java or C# where the char { and } are used to differentiate a block of code. Pay attention to you formatting, indentation.

 

#Notice: The char , (comma) is used to tell that something is going to continue on the same print line, within the same block of code. See example above.

 

#Notice: Colons : differentiate clauses.

 

Importing modules

 

import numpy as np

 

A = np.random.normal(25.0, 5.0, 10)

print A

 

Data structures

 

Lists

 

Defining a list(Notice: The brackets [] define an mutable list):

x = [1, 2, 3, 4, 5, 6]

 

Printing the length of a list:

print len(x)

 

Sub setting lists:

 

First 3 elements(counting starts from zero):

x[:3]

 

Last 3 elements:

x[3:]

 

Last two elements from starting from the end of the list:

x[-2:]

 

Extend the list with a new list :

x.extend([7,8])

 

Add a new item to the list:

x.append(9)

 

Python is a weekly typed language which allows you to put whatever you want in a list:

 

Creating a multidimensional list:

y = [10, 11, 12]

listOfLists = [x, y]

listOfLists

 

Sort a list(descending):

z = [3, 2, 1]

z.sort()

 

Sort a list(ascending):

z.sort(reverse=True)

 

Tuples

 

Are just like lists but immutable.

You can not extend them append them, sort them etc. You can not change them.

 

Example:

 

#Tuples are just immutable lists. Use () instead of []

x = (1, 2, 3)

len(x)

 

y = (4, 5, 6)

 

listOfTuples = [x, y]

 

Tuples common usage for data science or data processing:

Is to use it to assign variables to input data that as it is read in.

 

This example creates variable with values from a “source” where data is split by the comma.

#Notice: It is important that you have the same about of variables in your tuple as you are retrieving/assigning from the data “source”.

(age, income) = “32,120000”.split(‘,’)

print age

print income

 

Dictionaries

 

A way to define a “lookup” table:

 

# Like a map or hash table in other languages

captains = {}

captains[“Enterprise”] = “Kirk”

captains[“Enterprise D”] = “Picard”

captains[“Deep Space Nine”] = “Sisko”

captains[“Voyager”] = “Janeway”

 

print captains[“Voyager”]

 

print captains.get(“Enterprise”)

 

for ship in captains:

print ship + “: ” + captains[ship]

 

If something is not found the result will be none:

print captains.get(“NX-01”)

 

Functions

 

Let you repeat a set of operation over and over again with different parameters.

 

Notice: use def to define a function and  () chars to define the parameters and use the return keyword to return value from the function.

 

def SquareIt(x):

return x * x

 

print SquareIt(2)

 

Pass functions around as parameters

#Notice: You have to make sure that what you are typing is correct because there is no strong typing in Python. Typing the wrong function name will cause errors.

 

#You can pass functions around as parameters

def DoSomething(f, x):

return f(x)

 

print DoSomething(SquareIt, 3)

 

Lambda functions

Is Functional programming: You can inline a function into a function

 

#Notice: lambda keyword is telling that you are defining a inline function to be used where you put it. In the example below inside a function parameter named x followed by a colon : character followed by what the function actually does. To pass in multiple parameters to a lambda function use the comma , to separate the variables.

 

#Lambda functions let you inline simple functions

print DoSomething(lambda x: x * x * x, 3)

 

Boolean Expressions

 

Valye is false

print 1 == 3

 

Value is true(or keyword check which is true)

print (True or False)

 

Check if something is a certain value( Use the is keyword)

print 1 is 3

 

If else clauses

 

if 1 is 3:

print “How did that happen?”

elif 1 > 3:

print “Yikes”

else:

print “All is well with the world”

 

Looping

 

Normal looping

for x in range(10):

print x,

 

Continue and Break

 

#Process only the first 5 items but skip the number one

for x in range(10):

if (x is 1):

continue

if (x > 5):

break

print x,

 

While

 

x = 0

while (x < 10):

print x,

x += 1

 

 

Hiding and showing HTML elements with ASP .NET

Hi,

Ok, this is probably a quite simple thing to do and maybe everyone knows it BUT just in case… :).

Well, you need two things a C# code(or some other way to ouput HTML) to generate and anchor link by which to display or hide a given HTML element.

In this case, let’s say that you have a DIV element. You assign as the ID value the client ID which your control receives from ASP .NET(notice that the unique ID or the ID but the ClientID, it is HTML friendly).

Then you would do something like the code below. You are calling a JavaScript function which receives as parameters the full ID for the DIV element and the start of the DIV full id.

The idea is to be able to identify all of the elements which are under this same hide and show logic while still being able to identify a single item.

Exmaple ID:
id =”cars_ASP.NETUserControlClientID_carnumber”

The bolded part would be used to identify ALL of the items which need be processed at the same time. While the non-bolded value(carnumber) is the identifier for a single item.

The C# code below creates an anchor calling the function below the C# code. Notice the href definition “javascript:void(0)“, this is to avoid page jump in certain browsers and their versions.

String.Format("<a href=\"javascript:void(0)\" onclick=\"showInfo('{0}','{2}')\">{1}</a>", "HTML Element ID to find unique counter or ID" + this.ClienID, "The link title/name", this.ClienID);

function showInfo(id, controlUniqueID) {
// Search for all items and hide them
 $('*[id*=' + controlUniqueID + ']').each(function () {
 $(this).hide();
 });

// Next open only the item which you want to see
 if ($('#' + id).css('display') == 'none') {
 $('#' + id).show();
 }
 else {
 $('#' + id).hide();
 }

 }

Export SharePoint solution packages from your environment

Hi,

I created a script that might help someone out there who wants to backup their SharePoint solution packages. This script is able to export specific solutions or all if no solution names are passed to the script.

Sample script calling for specific solutions:

.\script.ps1 –Solutions MYWSPNUM1.wsp,MYWSPNUM2.wsp

Or if you want to export all available solutions then simply call the script without any parameters:

.\script.ps1

# Get Script params, in this case solution names to the -Solution attribute. Separate solutions names by , char
param([String[]] $Solutions)

Add-PSSnapin Microsoft.SharePoint.PowerShell –erroraction SilentlyContinue

#==================================================================================
# Functions definitions
#==================================================================================

#———————————————————————————-
# This function will export all available solutions in your environment
#———————————————————————————-
function ExportAllSolutions
{
$location = get-location
Write-Host Exporting all available solutions to: $location
foreach ($solution in Get-SPSolution)
{
$id = $Solution.SolutionID
$title = $Solution.Name
$filename = $Solution.SolutionFile.Name

try {
$solution.SolutionFile.SaveAs(“$(get-location)\$filename”)
Write-Host “Exported solution package – ‘$title’:” -foreground green
}
catch
{
Write-Host ” Error with solution package – ‘$title’: $_” -foreground red
}
}
}

#———————————————————————————-
# This Function will export a single solution by solution name
#———————————————————————————-
function ExportSolution
{
param([String] $solutionName)
$location = get-location
Write-Host Exporting solution to: $location
$Solution = Get-SPSolution -Identity $solutionName

$id = $Solution.SolutionID
$title = $Solution.Name
$filename = $Solution.SolutionFile.Name

try {
$solution.SolutionFile.SaveAs(“$(get-location)\$filename”)
Write-Host “Exported solution package – ‘$title’:” -foreground green
}
catch
{
Write-Host ” Error with solution package – ‘$title’: $_” -foreground red
}

}

#==================================================================================
# End of function definitions
#==================================================================================

#==================================================================================
# Main operations for the script
#==================================================================================

# If solutions names are passed then export only those solutions
if($Solutions.count -gt 0)
{
foreach ($solutionName in $Solutions)
{
Write-Host $solutionName
ExportSolution $solutionName
}
}
# If no solultions passed then export all solutions
else
{
ExportAllSolutions
}
#==================================================================================
# End of main operations
#==================================================================================