Create Site Column Using Power Shell and Server Object Model

Leave a Comment
Hi Guys, Thanks for visiting Blog . In one of my previous posts We have created Site Column in SharePoint Site using Out of box feature. In current post ,we are 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 = ''
 $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)
            {                
                //Exception Handling
            }
        }

Related Post

0 comments:

Post a Comment