Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set internal names of new SharePoint fields with PowerShell?

I'm trying to add a new field to a SharePoint list and set its internal name. I have both the static name and display name specified but I can't figure out why the internal name gets set as First_x0020_Name.

$web = Get-SPWeb 'https://server'
$list = $web.Lists['listName']
$newFieldXML = '<Field Type="Text" StaticName="FirstName" DisplayName="First Name"></Field>'
$list.Fields.AddFieldAsXml($newFieldXML)
like image 776
cooper Avatar asked Mar 13 '23 20:03

cooper


2 Answers

This simply works for me-

XML should be of format:

$newFieldXML = '<Field Type="Text" Name="FirstName" StaticName="FirstName" DisplayName="First Name"></Field>'

In PowerShell use [Microsoft.SharePoint.SPAddFieldOptions]::AddFieldInternalNameHint as third parameter of AddFieldAsXml function

$spListFields = $spList.Fields.AddFieldAsXml($newFieldXML, $true, [Microsoft.SharePoint.SPAddFieldOptions]::AddFieldInternalNameHint)
like image 58
Saurabh Verma Avatar answered Apr 26 '23 15:04

Saurabh Verma


It looks like AddFieldAsXml cannot be used to set the internal name

According to the article, if you want to use AddFieldAsXml to set the internal name you need to:

  1. Define your CAML so that the Internal Name you want to use is actually set as the Display Name
  2. Create the field with the call to AddFieldAsXml
  3. After the field is created, retrieve it using the internal name and set the Title property to the real Display Name you wanted it to be in the first place

You need two additional steps: retrieve the field and set the internal name

like image 31
Matt Avatar answered Apr 26 '23 14:04

Matt