Add Column to List and Content type Using Powershell

Below is the code you need to execute to add a column to List and Content type using PowerShell. Copy below code to notepad, rename the notepad with CreateField.ps1 and then execute the code from PowerShell.

PowerShell

#####################Code Starts

# Add PsSnapin if not already added

if ( (Get-PSSnapin -Name Microsoft.Sharepoint.Powershell -ErrorAction SilentlyContinue) -eq $null )

{

Add-PsSnapin Microsoft.Sharepoint.Powershell

}

# Call the function with WebURL, List Name – where you want to add column

# FieldName – the nae of the filed you want to add – type is hardcoded in below function

# Contenttype name – the content type name you want to add field to

function CreateColumn($webUrl, $listName, $fieldName, $contentTypeName )

{ $web = Get-SPWeb $webUrl

Write-Host “$($web.URL)”

$pageList = $web.Lists[$listName]

Write-Host “$($pageList.URL)”

$pageFieldisNewTillDate = $pageList.Fields.Add($fieldName, “DateTime”, 0)

$pageList.Fields[$pageFieldisNewTillDate].Title = $fieldName

$pageList.Fields[$pageFieldisNewTillDate].Description = “Description here”

$pageList.Fields[$pageFieldisNewTillDate].DisplayFormat = “DateOnly”

$pageList.Fields[$pageFieldisNewTillDate].Update()

$pageList.Update();

$field = $pageList.Fields[$fieldName]

Write-Host “Field created” + “$($field)”

$fieldlink = New-Object Microsoft.SharePoint.SPFieldLink $field

#Write-Host “$($fieldlink)”

$contentTypeContact = $pageList.ContentTypes[$contentTypeName]

Write-Host “$($contentTypeContact.Title)”

#add the new field to content type you need

$contentTypeContact.FieldLinks.Add($fieldlink)

$contentTypeContact.Update()

$web.Dispose();

}

# Function is called with valied input parameters

CreateColumn -webUrl “https://xxx.com/Contacts” -listName “Pages” -fieldName “isValidTillDate” -contentTypeName “Contacts”

CreateColumn -webUrl “https://xxx.com/KnowledgeUpdate” -listName “Pages” -fieldName “isValidTillDate” -contentTypeName “KnowledgeUpdate”

#####################Code Ends

Feel free to drop me email on bipinparshottam@gmail.com, skype:bipin.pankhania incase of queries.

Advertisements