top of page
Writer's pictureVijai Anand Ramalingam

How to enforce unique value for a column in SharePoint 2010 using powershell

In this article we will be seeing how to enforce unique value for a list or library column in SharePoint 2010 using C# and powershell.

In SharePoint 2010 we can enforce uniqueness on values in a list or library column, effectively creating a primary key. When you create a column in the list or library you could see an option "Enforce Unique Values" where you can enforce uniqueness. When you enforce uniqueness on a Lookup column, the list item in the target list can have only one list item looking up to it from the child list.

Using C#:

a. Open Visual Studio 2010.

b. Create Console application.

c. Replace the code with the following.

  1. using System;

  2. using System.Collections.Generic;

  3. using System.Linq;

  4. using System.Text;

  5. using Microsoft.SharePoint;

  6. namespace EnforceUniqueValue

  7. {

  8. class Program   

  9. {

  10. static void Main(string[] args)       

  11. {

  12. using (SPSite site = new SPSite("http://serverName:1111/"))           

  13. {

  14. using (SPWeb web = site.RootWeb)               

  15. {

  16. SPList list = web.Lists.TryGetList("cl");

  17. SPField field = list.Fields["TestCol"];                   

  18. field.Indexed = true;                   

  19. field.EnforceUniqueValues = true;                   

  20. field.Update();               

  21. }           

  22. }       

  23. }   

  24. }

  25. }

d. Hit F5.













Using PowerShell:

  1. $siteURL="http://serverName:1111/"

  2. $listName="cl"

  3. $fieldName="TestCol"

  4. $site=Get-SPSite $siteURL

  5. $web=$site.RootWeb

  6. $list=$web.Lists.TryGetList($listName)

  7. $field=$list.Fields[$fieldName]

  8. $field.Indexed=$true

  9. $field.EnforceUniqueValues=$true

  10. $field.Update()

0 comments

Comments


bottom of page