Explore the Experience in SharePoint 2013

Monday, December 1, 2014

Create Site Column Using Power Shell and Server Object Model as well.

No comments
Hi Guys,

Thanks for visiting my blog .

 In one of my previous posts  i have created Site Column in SharePoint Site using Out of box feature.

In my current post ,am going to create a Site Column using Power Shell Script  and  Server  object Model as well.


First , I will show the Power Shell Script to create a site Column .

$site = Get-SPSite -Identity "Site URL"  // Add the Site URL here
 $web = $site.RootWeb
 $fieldXML = '<Field Type="Text"
 Name="EmpName"
 Description="Employee Name Column Info."
 DisplayName="EmpName"
 Group="EmployeeInformation"
 Hidden="FALSE"
 Required="FALSE"
 ShowInDisplayForm="TRUE"
 ShowInEditForm="TRUE"
 ShowInListSettings="TRUE"
 ShowInNewForm="TRUE"></Field>'
 $web.Fields.AddFieldAsXml($fieldXML)
 $web.Dispose()
 $site.Dispose()


Note : Save the Script in notepad and save the text file with .ps1 extension in  drive .
           Copy the Script location with  extension.
          Open-->Power Shell(Run As Administrator)

Now you can check the site Column created under Group "EmployeeInformation".


Second  , I will show how to  create a site Column  using C# (Programatically)..



        private static void CreateSiteColumn()
        {
            try
            {
                string SiteColumnName = "IndiaMyCountry";
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite("Server URL"))
                {
                    SPWeb web = site.RootWeb;
                    //Create Site Column
                   
                    //Add choice Field "India"
                    if (!web.Fields.ContainsField(SiteColumnName)) 
                    {
                        string countryField = web.Fields.Add(SiteColumnName, SPFieldType.Choice, true);
                        //Set the Field Properties
                        SPFieldChoice CityInIndia =(SPFieldChoice)web.Fields.GetField(SiteColumnName);
                        //Set the group for the Site column
                        CityInIndia.Group = "States";  
                        //Add the choices
                        string[] States = new string[] { "TamilNadu", "Kerala", "Andhr Pradesh","karnataka"};
                        CityInIndia.Choices.AddRange(States);
                        //Set the default value
                        CityInIndia.DefaultValue = "TamilNadu";
                        //Set Fillable value
                        CityInIndia.FillInChoice = true;
                        //Update the field
                        CityInIndia.Update();
                    }
                }
                       
            });
            }
            catch (Exception ex)
            {
               
                throw ex;
            }
        }

No comments :

Post a Comment