How to Add Date Time Field to SharePoint List using PowerShell?
Requirement: Add Date and Time Column to SharePoint list using PowerShell.
PowerShell Script to add Date and Time Column to SharePoint list:
If you need to add a date-time field to a SharePoint list, you can do so easily using PowerShell. In this guide, we will walk you through the steps of how to add a date and time field to a SharePoint list using PowerShell.
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
#Processing Variables
$WebURL="https://portal.crescent.com/sites/Sales"
$ListName="Vendors"
$FieldName="Date of Contract"
$RequiredField=$false
#Get Objects
$Web = Get-SPWeb $WebURL
$List= $Web.Lists[$ListName]
#Add Date and Time Column
$List.Fields.Add($FieldName,"DateTime", $RequiredField)
This Adds a new field.
Set Date Time Column Settings using PowerShell:
While the above code adds a new field to a given list, there are additional settings on the column such as: Display Format, Default Value, etc. can be set using PowerShell.
PowerShell to Update Date Time Column Settings:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
#Processing Variables
$WebURL="https://portal.crescent.com/sites/Sales"
$ListName="Vendors"
$FieldName="Date of Contract"
#Get Objects
$Web = Get-SPWeb $WebURL
$List= $Web.Lists[$ListName]
#Set Column Settings
$List.Fields[$FieldName].Description = "Enter Date of Join"
#Enforce unique
$List.Fields[$FieldName].EnforceUniqueValues = $false
#Required
$List.Fields[$FieldName].Required = $true
#Date Time Display Format
$List.Fields[$FieldName].DisplayFormat = "DateOnly"
#Default Value
#$List.Fields[$FieldName].DefaultValue="[today]
#Formula
$List.Fields[$FieldName].DefaultFormula = "=[Today]+7"
#Friendly Display Format
$List.Fields[$FieldName].FriendlyDisplayFormat="Disabled"
$List.Fields[$FieldName].update()
Refer to this MSDN link for the complete field properties reference: SPFieldDateTime properties