Users

Create a User or Group Site Column in SharePoint with PowerShell

The following snippet creates a User Site Column in SharePoint on-prem. Notice that the code checks for the existence of the site column before creating it – because typically you will be using this in a larger provisioning script, and it makes sense to let your code run more than once – so as you build a solution, you can just add new elements and run it again.

# Connect to SharePoint Site
$web = get-spweb "https://server/sites/sitecollection/site"

# Set Site Column name etc
$site_column_internal_name = "MySiteColumn"
$site_column_display_name  = "My Site Column"
$site_column_group         = "My Site Columns"
$site_column_description   = "Simple example of site column"

if ($web.Fields.ContainsField($site_column_internal_name)){

    # Get Existing Site Column
    $site_column = $web.Fields.GetField($site_column_internal_name)
 
} else {

    # Create new site column
    $web.Fields.Add($site_column_internal_name, "User", $false) > $null
    $field = $web.Fields.GetField($site_column_internal_name)
    $field.Title = $site_column_display_name
    $field.Group = $site_column_group
    $field.Description = $site_column_description
    $field.AllowMultipleValues = $true
    $field.SelectionMode = [Microsoft.SharePoint.SPFieldUserSelectionMode]::PeopleAndGroups
    $field.Update() > $null
}

# instantiate field link object for field
$field_link = new-object Microsoft.SharePoint.SPFieldLink($field)

# add field link to existing content type
$content_type = $web.ContentTypes["My Content Type"]
$content_type.FieldLinks.Add($field_link) > $null

# release resources
$web.Close()
$web.Dispose()

Also notice that the site column will be provisioned in the web you connect to – but must be uniquely named across the entire site collection.

Posted by Jonathan Beckett in Notes, 0 comments