Saturday 21 February 2015

Attach Lookup Columns to document and document set content types using PowerShell

Below is the PowerShell code for adding user in Attach Lookups To Document And DocSet Content Types.
- Need to change some configure details in script.
- Need to chagne in CSV file like ContentType, SiteColumn and ColumnSetting.


Add-PSSnapin Microsoft.SharePoint.PowerShell -EA SilentlyContinue
Function CheckColumnExistsOnContentType{
Param($ContentType, $ColumnName)      
$Fields = $ContentType.Fields | ? {$_.InternalName -eq $ColumnName}
Write-Host $ColumnName $Fields
If($Fields -eq $Null){
Return $false
}
Else{
Return $true}      
}
 
    $SPSite = Get-SPSite -Identity http://serverName/
    $Web = $SPSite.RootWeb
    $Create = Import-Csv -path "C:\[location]\AttachLookupsToDocumentAndDocSetContentTypes.csv"
$Create
    ForEach($Row in $Create){
        $CT = $Web.ContentTypes[$Row.ContentType];
        $FieldAdd = $Web.Fields.GetFieldByInternalName($Row.SiteColumn)
  $ColumnExists = CheckColumnExistsOnContentType -ContentType $CT -ColumnName $FieldAdd
  if($ColumnExists -eq $True)
  {
   Write-Host "Attached Column" $FieldAdd.InternalName "to" $CT.name -ForegroundColor Cyan
   $FieldLink = New-Object Microsoft.SharePoint.SPFieldLink($FieldAdd)
   If($($_.'ColumnSetting') -eq "Hidden"){
    $FieldLink.Required = $false
    $FieldLink.Hidden = $true
   }
   ElseIf(($($_.'ColumnSetting') -eq "Required")){
        $FieldLink.Required = $true
   }
   Else{
       $FieldLink.Required = $false
   }
   $CT.FieldLinks.Add($FieldLink)
   $CT.Update($true)
   $Web.Update()
   $Web.Dispose()
   Write-Host " Column is added in Content Type" -ForegroundColor Green
  }
}

No comments:

Post a Comment