1

I want to know what is the best way to add a field in the list and change his display name. My case adds 20 fields in the list... but the code will get big...

This is my code(working)

$SPWebHolidays = Get-SPWeb -Identity $holidaysSite  
$pathToHolidaysWeb = $SPWebHolidays.url.trim() 

$SPTemplateHolidays = $SPWebHolidays.ListTemplates["Custom List"]  
$SPListsHolidays = $SPWebHolidays.Lists  
$SPListsHolidays.Add("Holidays", "Holidays", $SPTemplateHolidays)  
$SPListHolidays = $SPWebHolidays.GetList("$pathToHolidaysWeb/Lists/Holidays")  

$SPListHolidays.Fields.Add("Area", $spFieldTypeText, $false)  
$SPListHolidays.OnQuickLaunch = $true
$SPListHolidays.Update()  

$field = $SPListHolidays.Fields.GetFieldByInternalName("Area")
$field.Title = "чинаДиаанд"
$field.Update()

When i use :

$firstColXml = "<Field Type='Text' DisplayName='чинаДиаанд' StaticName='Area' Name='Area' />"
$SPListHolidays.Fields.AddFieldAsXml($firstColXml, $true,
[Microsoft.SharePoint.SPAddFieldOptions]::AddFieldToDefaultView)

my Internal Name of field is : enter image description here

1

You also have the option to add the fields as XML using the AddFieldAsXml method. When you use this, you can specify the XML string to create the field definition and it will eliminate the need to update the display name as you can specify the display name itself in the XML.

Check the below code:

$SPListHolidays = $SPWebHolidays.GetList("$pathToHolidaysWeb/Lists/Holidays") 

$firstColXml = "<Field Type='Text' Name='Area' StaticName='Area' DisplayName='чинаДиаанд'></Field>"

$secondColXml = "<Field Type='Text' Name='OtherColumn' StaticName='OtherColumn' DisplayName='Other Column'></Field>"

$SPListHolidays.Fields.AddFieldAsXml($firstNameColXml,$true,
[Microsoft.SharePoint.SPAddFieldOptions]::AddFieldInternalNameHint)

$SPListHolidays.Fields.AddFieldAsXml($secondColXml,$true,
[Microsoft.SharePoint.SPAddFieldOptions]::AddFieldInternalNameHint)

$SPListHolidays.OnQuickLaunch = $true
$SPListHolidays.Update()  

Reference - SPFieldCollection.AddFieldAsXml method

XML that you can build - Field Element (Field)

  • see my updated question – Goshky Oct 27 '17 at 7:56
  • 1
    can you try with edited answer ? have modified it to use AddFieldInternalNameHint – Gautam Sheth Oct 27 '17 at 9:09
1

Try to add the 20 fields in CSV file then loop for each field via foreach as the following

Import-Csv F:\fields.csv | ForEach-Object { 
    $Field= $_.Field
    $FieldDisplayName =  $_.FieldDisplayName
  // write your code

      }

The CVS file format should look like

Field,FieldDisplayName
Field1,FieldDisplayName1
Field2,FieldDisplayName2
Field3,FieldDisplayName3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.