SP16 PowerShell - How to update field DisplayName after add in List
-
04-01-2021 - |
题
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)
解决方案
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)
其他提示
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