Thursday 12 November 2015

PowerShell to change Content Type of Documents in a Document Library

PowerShell to change Content Type of Documents in a Document Library

SharePoint 2013, PowerShell 3.0

The Problem

A Document Library or Libraries have documents using metadata to differentiate files when Content Types are required.

The Approach

Iterate through all of the files in the document library to find a match to a given field (Title in this example) and then check it out and set the content type to the new type and check it back in with an appropriate version comment. Any new fields in the new content type will default to the column default. Does not enforce that required fields have values.

The Code

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue 
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint") > $null 

# The string that matches a given field that identifies the files to be changed
$beginCT = "Invoice"

#The name of the content type to update to
$newCTName = "Baers New Content Type"

# The web site in the collecton to which the content type change should apply
$site = "http://app1:31645/Baer's Shared Points"

#The internal name of the library - the default 'Shared Documents' is 'Documents'
$docLibName = "Documents"

#path to the log file/name.type (txt or csv). If not present, will create. If present, will overwrite
$outfile = "CTUpdate-log.csv"


$w = Get-SPWeb $site 
$list = $w.Lists[$docLibName]

$newCT = $list.ContentTypes["$newCTName"]
$newCTID = $newCT.ID

$count = 0

foreach ($listItem in $list.Items)
{
  $i =  $listItem["Title"]

  if (($i -like "*$beginCT*")) {
$count += 1
$file = $listItem.File 

$file.CheckOut()
write-host "Resetting content type for file" $listItem.Name "to" $newCT.Name -foregroundColor Green
$listItem["ContentTypeId"] = $newCTID
$listItem.Update()

$file.CheckIn("Content type changed to " + $newCT.Name, 1) 
$logItem = ""+$listItem["Name"], $listItem["Content Type"]+"" | Out-File $outfile -Append
  }    
}
$logItem = "Total files with Content Type changed to "+ $newCT.Name+": "+ $count +"" | Out-File $outfile -Append
$w.Dispose()

The Result






Going Forward

Error capture on variables is good. Making sure the library is a document library would be good too.
Add looping for multiple content types and match values, Add looping to read and apply changes to multiple libraries, Read values from a csv or xml file.

No comments:

Post a Comment