PnP PowerShell: Working with different types of field using Add-PnPFieldFromXML

PnP PowerShell is a vast library of PowerShell commands that helps us in performing simple to complex tasks in SharePoint very easily. Tasks may be related to branding, lists, libraries, content types, site provisioning, Graph etc.

These commands are CSOM based and can be utilized for both SharePoint Online and On-Premise (2013 and 2016).

Installation

These cmdlets can be installed by downloading the setup files or using PowerShell Gallery (recommended) for the required SharePoint version.

Latest version is 2.26.1805.1 released in May 2018.

Check if PnP is installed or not

Open Windows PowerShell and run below command-

Get-Command -Module *PnP*

If installed it will return all the available commands along with version and source else it will return empty.

GetCommand

Using the library

To use the commands, first we need to connect to tenant or any SharePoint site by using below command-

Connect-PnPOnline -Url "<Site Url>"

This will prompt for username and password and creates context for other commands.

connect

After successful connect, type below command to check connection-

Get-PnPWeb

This will return the Title, Url and Id of the connected site. That means our connection is successful and commands are working fine.

Web

Add Field

Considering you are still connected to SharePoint Site. If not please follow above steps to connect.

To add a field as a Site Column or to a list/library, we can use two types of command-

  • Add-PnPField
  • Add-PnPFieldFromXML

Add-PnPField

This command is used to add field as Site Column or to a list by specifying the command attributes. Example, lets create a Single Line of Text field –

As Site Column
Add-PnPField -DisplayName "Demo Name" -InternalName "DemoName" -Type Text -Group "Demo Group"
As List Column
Add-PnPField -DisplayName "Demo Name" -InternalName "DemoName" -Type Text -Group "Demo Group" -List "Demo list" -AddToDefaultView

 Add-PnPFieldFromXML

This command is used to create field using specified XML. If you feel comfortable creating fields by specifying the XML, then this command is very helpful. 

First. lets assign the field XML to a variable like below-

$fieldXml = '<Field Type="Text" DisplayName="Demo Name" Required="TRUE" ID="{1b5da3cb-91a6-488b-93f6-7620105fa77e}" MaxLength="255" StaticName="DemoName" Name="DemoName" Description="Provide Name for the Demo" />'
 Add as a Site Column
Add-PnPFieldFromXml -FieldXml $fieldXml
Add to a List
Add-PnPFieldFromXml -List "Demo List" -FieldXml $fieldXml

XML Format of Fields based on Type

A field XML is formed using a set of attributes, some which are mandatory and some are optional. Some of the commonly used attributes are explained below-

  • Mandatory Attributes
    • Type – Defines the type of field like Text, DateTime etc.
    • DisplayName – Display name of the field like “User Name”
    • Name – Internal Name of the field like “UserName”
    • ID – Unique GUID for the field
  • Optional Attributes
    • ShowInNewForm – Defines whether field is displayed on New form.
    • ShowInEditForm – Defines whether field is displayed on Edit form.
    • ShowInDisplayForm – Defines whether field is displayed on Display form.
    • ShowInViewForms – Defines whether field is displayed in pages that are used to view list data.
    • StaticName – Usually similar to Internal Name but not necessarily unique. Understand the difference between DisplayName, InternalName and StaticName here.
    • Indexed – Defines whether field is indexed or not
    • Required – Determines whether a field is mandatory or not.
    • EnforceUniqueValues – To enforce uniqueness in field values.
    • Description – Allows to provide description for the field.
    • Group – Defines the column group. Mainly used when creating Site Column.
    • ReadOnly – Defines whether field value can be modified or not.

Single Line of Text

 <Field Type="Text" DisplayName="Demo Name" Required="TRUE" ID="{1b5da3cb-91a6-488b-93f6-7620105fa77e}" MaxLength="255" StaticName="DemoName" Name="DemoName" Description="Provide Name for the Demo" />

Attributes Used-

  • MaxLength – Defines maximum no. of characters that can be typed in field.

Multiple Lines of Text

PLAIN TEXT
<Field Type="Note" DisplayName="DemoDescription" Required="FALSE" ID="{4d3377d1-26fd-4037-bb8f-1b1777ad7626}" NumLines="6" RichText="FALSE" Sortable="FALSE" StaticName="DemoDescription" Name="DemoDescription" Description="Please provide short description of demo"/>

RICH TEXT
<Field Type="Note" DisplayName="DemoDescription" Required="FALSE" ID="{4d3377d1-26fd-4037-bb8f-1b1777ad7626}" NumLines="6" RichText="TRUE" RichTextMode="Compatible" IsolateStyles="FALSE" Sortable="FALSE" AppendOnly="FALSE" StaticName="DemoDescription" Name="DemoDescription" Description="Please provide short description of demo"/>

ENHANCED RICH TEXT
<Field Type="Note" DisplayName="DemoDescription" Required="FALSE" ID="{4d3377d1-26fd-4037-bb8f-1b1777ad7626}" NumLines="6" RichText="TRUE" RichTextMode="FullHtml" IsolateStyles="TRUE" Sortable="FALSE" AppendOnly="FALSE" StaticName="DemoDescription" Name="DemoDescription" Description="Please provide short description of demo"/>

Attributes Used-

  • RichText – If false then field is Plain Text else Rich text.
  • RichTextMode – Defines whether rich text (Compatible) or enhanced rich text (FullHtml)
  • Isolated – If true, server re-writes the html of field to ensure it does not interfere with the rendering of page.
  • Sortable – Defines whether field can be sorted or not.
  • Numlines – Defines the number of lines to display in field.

 Choice

CHOICE DROP DOWN
<Field Type="Choice" DisplayName="Demo Status" Required="FALSE" ID="{c70cde32-9afa-4137-be86-4cb745626d09}" Format="Dropdown" FillInChoice="FALSE" StaticName="DemoStatus" Name="DemoStatus" Description="Please select appropriate status for the demo">
  <Default>To be started</Default>
  <CHOICES>
    <CHOICE>To be started</CHOICE>
    <CHOICE>In Progress</CHOICE>
    <CHOICE>Completed</CHOICE>
  </CHOICES> 
</Field>

CHOICE RADIO BUTTON
<Field Type="Choice" DisplayName="Demo Status" Required="FALSE" ID="{c70cde32-9afa-4137-be86-4cb745626d09}" Format="RadioButtons" FillInChoice="FALSE" StaticName="DemoStatus" Name="DemoStatus" Description="Please select appropriate status for the demo">
   <Default>To be started</Default>
   <CHOICES>
     <CHOICE>To be started</CHOICE>
     <CHOICE>In Progress</CHOICE>
     <CHOICE>Completed</CHOICE>
   </CHOICES> 
</Field>

CHOICE CHECKBOX
<Field Type="MultiChoice" DisplayName="Demo Status" Required="FALSE" ID="{c70cde32-9afa-4137-be86-4cb745626d09}" FillInChoice="FALSE" StaticName="DemoStatus" Name="DemoStatus" Description="Please select appropriate status for the demo">
   <Default>To be started</Default>
   <CHOICES>
     <CHOICE>To be started</CHOICE>
     <CHOICE>In Progress</CHOICE>
     <CHOICE>Completed</CHOICE>
   </CHOICES> 
</Field>

Attributes Used-

  • Type – If Checkbox, use “MultiChoice”, else “Choice”
  • Format – Defines mode of Choice field – Only for Drop down or Radio button
  • FillInChoice – If True, allows user to enter custom value.

Number

NUMBER DISPLAY
<Field Type="Number" DisplayName="Demo Quantity" Description="" ID="{27d81055-f208-41c9-a976-61c5473eed4a}" Required="FALSE" Min="1" Max="50" Decimals="2" StaticName="DemoQuantity" Name="DemoQuantity" />

PERCENTAGE DISPLAY
<Field Type="Number" DisplayName="Demo Share" Description="" ID="{27d81055-f208-41c9-a976-61c5473eed4a}" Required="FALSE" Percentage="TRUE" StaticName="DemoShare" Name="DemoShare" />

Attributes Used-

  • Min – Optional. Defines the minimum value allowed. Default is blank.
  • Max – Optional. Defines the maximum value allowed. Default is blank.
  • Percentage – If set, displays number along with percentage sign.

Currency

<Field Type="Currency" DisplayName="Demo Cost" Description="" ID="{27d81055-f208-41c9-b656-61c5473eed4a}" Required="FALSE" LCID="1033" Decimals="2" StaticName="DemoCost" Name="DemoCost" />

Attributes Used-

  • LCID – Defines the currency symbol along with the format of field’s value and also position of currency symbol. 1033 sepicifies “English (United States)” and formats currency value using $ symbol.

Date and Time

<Field Type="DateTime" DisplayName="Demo Date" Required="FALSE" ID="{f451a866-c1de-4a78-b7f4-17fab6eec7d9}" Format="DateOnly" FriendlyDisplayFormat="Disabled" StaticName="DemoDate" Name="DemoDate"/>

Attributes Used-

  • Format – Optional. Can be set to “DateOnly” or “DateTime”. Default is “DateOnly”.
  • FriendlyDisplayFormat – Optional. Can be set to “Disabled” means Standard display or “Relative” means Friendly display.

Lookup

<Field Type="Lookup" DisplayName="Demo Topics" Required="FALSE" EnforceUniqueValues="FALSE" List="<guid of lookup list>" ShowField="Title" UnlimitedLengthInDocumentLibrary="FALSE" RelationshipDeleteBehavior="None" ID="{1654bed4-1798-476b-8e3d-301b8b760e8f}" StaticName="DemoLookup" Name="DemoLookup" />

Attributes Used-

  • List – GUID of the lookup list.
  • ShowField – Lookup list column to be displayed.
  • UnlimitedLengthInDocumentLibrary – Optional. Specifies whether to allow unlimited text in lookp field. Default is FALSE.
  • RelationshipDeleteBehavior – Optional. Specifies the delete behavior of the lookup field. Can be “None”, “Cascade” or “Restrict”. Default is None.
    • Cascade – If item in source (lookup) list is deleted, then all related dependent items in current list are deleted.
    • Restrict – It prevents deleting an item in source (lookup) list, if related dependent items are present in current list.

Yes/No

<Field Type="Boolean" DisplayName="Demo Completed" ID="{65700eae-deb3-437f-8447-cf1197236fbf}" Name="DemoCompleted" StaticName="DemoCompleted"  Description="">
   <default>0</default>
</Field>

Attributes Used-

  • Default – 0 means No and 1 means Yes. Default is 1.

Person or Group

SINGLE USER
<Field Type="User" DisplayName="Demo Presentor" List="UserInfo" Required="FALSE" ID="{fafe9a69-aabf-4e16-bc82-95c0625e5960}" ShowField="EMail" UserSelectionMode="PeopleOnly" StaticName="DemoPresentor" Name="DemoPresentor" Description=""/>

MULTI USER
<Field Type="UserMulti" DisplayName="Demo Presentors" List="UserInfo" Required="FALSE" ID="{bd66d0d0-c441-4ce3-909a-204ff01cdcb7}" ShowField="EMail" UserSelectionMode="PeopleOnly" StaticName="DemoPresentors" Name="DemoPresentors" Mult="TRUE" />

USER AND GROUP
<Field Type="User" DisplayName="Demo Approvers" List="UserInfo" Required="FALSE" ID="{fafe9a69-aabf-4e16-bc82-95c0625e5960}" ShowField="EMail" UserSelectionMode="PeopleAndGroups" UserSelectionScope="5" StaticName="DemoApprovers" Name="DemoApprovers" Description=""/>

Attributes Used-

  • Type – “User” means single selection and “UserMulti” means multiple selection.
  • List – Defines the UserInformation List
  • ShowField – Defines the user property  like Email, Name (with presence)  etc. to be displayed as field value. Only one user property can be provided. Default is ImnName.
  • UserSelectionMode – “PeopleOnly” means only users an be selected and “PeopleAndGroups” allows both user and SharePoint group to be selected. Default is “PeopleOnly”.
  • UserSelectionScope – Optional. Allows to restrict the selection from one SharePoint group only. Acepts group Id.
  • Mult – Used if type is “UserMulti” to allow selection of multiple users.

Hyperlink or Picture

HYPERLINK
<Field Type="URL" DisplayName="Demo Link" ID="{bd66d0d0-c441-4ce3-909a-204ff01cdcc8}" Format="Hyperlink" StaticName="DemoLink" Name="DemoLink"/>

PICTURE
<Field Type="URL" DisplayName="Demo Image" ID="{bd66d0d0-c441-4ce3-909a-204ff01cdcc8}" Format="Image" StaticName="DemoImage" Name="DemoImage"/>

Attributes Used-

  • Format – “Hyperlink” means display link and “Image” means display picture. Default is Hyperlink.

Task Outcome

<Field Type="OutcomeChoice" DisplayName="Demo Outcome" Required="FALSE" EnforceUniqueValues="FALSE" Indexed="FALSE" ID="{3253b0c6-a433-4cd7-bfbc-97eee8b68529}" StaticName="DemoOutcome" Name="DemoOutcome">
   <Default>Approved</Default>
   <CHOICES>
   <CHOICE>Approved</CHOICE>
   <CHOICE>Rejected</CHOICE>
   <CHOICE>ReferBack</CHOICE>
   </CHOICES>
</Field>

Similar to Choice field except type which is “OutcomeChoice”. Represents an outcome choice field.

 

Extras

To get details of any command like what all attributes are associated to the command, syntax, examples etc., use below commands-

Get Command Syntax
PS C:\WINDOWS\System32> Get-Help "Add-PnPField"
NAME
 Add-PnPField
SYNOPSIS
 Add a field
SYNTAX
 Add-PnPField [-AddToDefaultView <SwitchParameter>] [-Required <SwitchParameter>] [-Group <String>] [-Web
 <WebPipeBind>] [-Connection <SPOnlineConnection>] [<CommonParameters>]

Add-PnPField -List <ListPipeBind> -Field <FieldPipeBind> [-Web <WebPipeBind>] [-Connection <SPOnlineConnection>]
 [<CommonParameters>]

Add-PnPField -DisplayName <String> -InternalName <String> -Type <FieldType> [-List <ListPipeBind>] [-Id
 <GuidPipeBind>] [-AddToDefaultView <SwitchParameter>] [-Required <SwitchParameter>] [-Group <String>]
 [-ClientSideComponentId <GuidPipeBind>] [-ClientSideComponentProperties <String>] [-Choices <String[]>] [-Formula
 <String>] [-Web <WebPipeBind>] [-Connection <SPOnlineConnection>] [<CommonParameters>]

Add-PnPField -DisplayName <String> -InternalName <String> -Type <FieldType> [-Id <GuidPipeBind>]
 [-ClientSideComponentId <GuidPipeBind>] [-ClientSideComponentProperties <String>] [-Choices <String[]>] [-Formula
 <String>] [-Web <WebPipeBind>] [-Connection <SPOnlineConnection>] [<CommonParameters>]

DESCRIPTION
 Adds a field to a list or as a site column
RELATED LINKS
 SharePoint Developer Patterns and Practices: http://aka.ms/sppnp
REMARKS
 To see the examples, type: "get-help Add-PnPField -examples".
 For more information, type: "get-help Add-PnPField -detailed".
 For technical information, type: "get-help Add-PnPField -full".
 For online help, type: "get-help Add-PnPField -online"
Get Command Examples
PS C:\WINDOWS\System32> Get-Help "Add-PnPField" -example
NAME
 Add-PnPField
SYNOPSIS
 Add a field
------------------EXAMPLE 1---------------------
PS:> Add-PnPField -Type Calculated -InternalName "C1" -DisplayName "C1" -Formula ="[Title]"
Adds a new calculated site column with the formula specified

------------------EXAMPLE 2---------------------
PS:> Add-PnPField -List "Demo list" -DisplayName "Location" -InternalName "SPSLocation" -Type Choice -Group "Demo Group" -AddToDefaultView
 -Choices "Stockholm","Helsinki","Oslo"
This will add a field of type Choice to the list "Demo List".

------------------EXAMPLE 3---------------------
PS:>Add-PnPField -List "Demo list" -DisplayName "Speakers" -InternalName "SPSSpeakers" -Type MultiChoice -Group "Demo Group" -AddToDefaultView
 -Choices "Obiwan Kenobi","Darth Vader", "Anakin Skywalker"
This will add a field of type Multiple Choice to the list "Demo List". (you can pick several choices for the same item)
Get Detailed Information
PS C:\WINDOWS\System32> Get-Help "Add-PnPField" -detailed
NAME
 Add-PnPField
SYNOPSIS
 Add a field
SYNTAX
 Add-PnPField [-AddToDefaultView <SwitchParameter>] [-Required <SwitchParameter>] [-Group <String>] [-Web <WebPipeBind>] [-Connection
 <SPOnlineConnection>] [<CommonParameters>]

Add-PnPField -List <ListPipeBind> -Field <FieldPipeBind> [-Web <WebPipeBind>] [-Connection <SPOnlineConnection>] [<CommonParameters>]

Add-PnPField -DisplayName <String> -InternalName <String> -Type <FieldType> [-List <ListPipeBind>] [-Id <GuidPipeBind>] [-AddToDefaultView
 <SwitchParameter>] [-Required <SwitchParameter>] [-Group <String>] [-ClientSideComponentId <GuidPipeBind>] [-ClientSideComponentProperties
 <String>] [-Choices <String[]>] [-Formula <String>] [-Web <WebPipeBind>] [-Connection <SPOnlineConnection>] [<CommonParameters>]

Add-PnPField -DisplayName <String> -InternalName <String> -Type <FieldType> [-Id <GuidPipeBind>] [-ClientSideComponentId <GuidPipeBind>]
 [-ClientSideComponentProperties <String>] [-Choices <String[]>] [-Formula <String>] [-Web <WebPipeBind>] [-Connection <SPOnlineConnection>]
 [<CommonParameters>]

DESCRIPTION
 Adds a field to a list or as a site column
PARAMETERS
 -AddToDefaultView [<SwitchParameter>]
 Switch Parameter if this field must be added to the default view
-Choices [<String[]>]
 Specify choices, only valid if the field type is Choice
-ClientSideComponentId [<GuidPipeBind>]
 The Client Side Component Id to set to the field
-ClientSideComponentProperties [<String>]
 The Client Side Component Properties to set to the field
-DisplayName <String>
 The display name of the field
-Field <FieldPipeBind>
 The name of the field, its ID or an actual field object that needs to be added
-Formula [<String>]
 Specify the formula. Only available if the field type is Calculated
-Group [<String>]
 The group name to where this field belongs to
-Id [<GuidPipeBind>]
 The ID of the field, must be unique
-InternalName <String>
 The internal name of the field
-List [<ListPipeBind>]
 The name of the list, its ID or an actual list object where this field needs to be added
-Required [<SwitchParameter>]
 Switch Parameter if the field is a required field
-Type <FieldType>
 The type of the field like Choice, Note, MultiChoice
-Connection [<SPOnlineConnection>]
 Optional connection to be used by the cmdlet. Retrieve the value for this parameter by either specifying -ReturnConnection on
 Connect-PnPOnline or by executing Get-PnPConnection.
-Web [<WebPipeBind>]
 This parameter allows you to optionally apply the cmdlet action to a subweb within the current web. In most situations this parameter is not
 required and you can connect to the subweb using Connect-PnPOnline instead. Specify the GUID, server relative url (i.e. /sites/team1) or web
 instance of the web to apply the command to. Omit this parameter to use the current web.
<CommonParameters>
 This cmdlet supports the common parameters: Verbose, Debug,
 ErrorAction, ErrorVariable, WarningAction, WarningVariable,
 OutBuffer, PipelineVariable, and OutVariable. For more information, see
 about_CommonParameters (https:/go.microsoft.com/fwlink/?LinkID=113216).

------------------EXAMPLE 1---------------------
PS:> Add-PnPField -Type Calculated -InternalName "C1" -DisplayName "C1" -Formula ="[Title]"
Adds a new calculated site column with the formula specified

------------------EXAMPLE 2---------------------
PS:> Add-PnPField -List "Demo list" -DisplayName "Location" -InternalName "SPSLocation" -Type Choice -Group "Demo Group" -AddToDefaultView
 -Choices "Stockholm","Helsinki","Oslo"
This will add a field of type Choice to the list "Demo List".

------------------EXAMPLE 3---------------------
PS:>Add-PnPField -List "Demo list" -DisplayName "Speakers" -InternalName "SPSSpeakers" -Type MultiChoice -Group "Demo Group" -AddToDefaultView
 -Choices "Obiwan Kenobi","Darth Vader", "Anakin Skywalker"
This will add a field of type Multiple Choice to the list "Demo List". (you can pick several choices for the same item)

REMARKS
 To see the examples, type: "get-help Add-PnPField -examples".
 For more information, type: "get-help Add-PnPField -detailed".
 For technical information, type: "get-help Add-PnPField -full".
 For online help, type: "get-help Add-PnPField -online"

References

https://github.com/SharePoint/PnP-PowerShell

https://docs.microsoft.com/en-us/powershell/sharepoint/sharepoint-pnp/sharepoint-pnp-cmdlets?view=sharepoint-ps

Please provide your valuable feedback.

5 thoughts on “PnP PowerShell: Working with different types of field using Add-PnPFieldFromXML

  1. Hi bro. This is an awesome article!
    But I have some questions for you, please help.

    This is my field xml:

    I got 3 issues:
    1. When i set ShowInNewForm=”False” the field still show on the new form.
    2. With Attributes ReadOnly=”True” The field does not create
    3. The field did not add to the view automatically? Do you have a powershell code to do it?

    Like

    • Hi Tan,

      Somehow your XML is not visible in comments (if added), but below are some of the points i would like to mention that you can try-
      1. ShowInNewForm=”FALSE” – boolean attributes are case-sensitive so value should be in CAPS.
      2. If you use ReadOnly attribute field is created but not visible under Columns, so best of creating a read-only field is using combination of ShowInDisplayForm=”TRUE”, ShowInNewForm=”FALSE” and ShowInEditForm=”FALSE”.
      3. Currently i do not have script but i will check and share.

      Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s