######################### Add SharePoint PowerShell Snapin ###############################################
if ( (Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null )
{
Add-PSSnapin Microsoft.SharePoint.Powershell
}
########################### End of Add SharePoint PowerShell Snapin ##################################
######################## Set Execution Path ################################################
$scriptBase = split-path $SCRIPT:MyInvocation.MyCommand.Path -parent
Set-Location $scriptBase
################################# End of Set Execution Path #################################
################################# Functions #####################################################
#$myCType = $null
function CreateField([string]$ColumnName, [string] $ColumnInternalName, [string] $DataTypes, [string] $DatatypeOptions, [string] $LookupListNM, [string] $LookupColumnNM)
{
try{
if($DataTypes-eq "singleline")
{
#SingleLine
$singleline=$fields.AddFieldAsXml("<Field Type='Text' DisplayName='$ColumnName' Required='False' MaxLength='255' Name='$ColumnInternalName' />",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Context.Load($fields)
$Context.Load($singleline)
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: SingleLine of Text field created successfully"
}
if($DataTypes-eq "multipleline")
{
#MulipleLine
if($DatatypeOptions -eq "plaintext")
{
#PlainText
$plaintxt=$fields.AddFieldAsXml("<Field Type='Note' DisplayName='$ColumnName' Required='FALSE' NumLines='6' RichText='FALSE'
Sortable='FALSE' Name='$ColumnInternalName'/>",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Context.Load($fields)
$Context.Load($plaintxt)
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: MultiLine of Plain Text field created successfully"
}
if($DatatypeOptions -eq "richtext")
{
#RichText
$richtxt=$fields.AddFieldAsXml("<Field Type='Note' DisplayName='$ColumnName' Required='FALSE' NumLines='6'
RichText='TRUE' RichTextMode='Compatible' Sortable='FALSE' Name='$ColumnInternalName' />",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Context.Load($fields)
$Context.Load($richtxt)
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: MultiLine of Rich Text field created successfully"
}
if($DatatypeOptions -eq "enhancedrichtext")
{
#EnhancedRichText
$enhancetxt=$fields.AddFieldAsXml("<Field Type='Note' DisplayName='$ColumnName' Required='FALSE' NumLines='6' RichText='TRUE'
RichTextMode='FullHtml' IsolateStyles='TRUE' Sortable='FALSE' Name='$ColumnInternalName' />",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Context.Load($fields)
$Context.Load($enhancetxt)
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: MultiLine of EnhancedRich Text field created successfully"
}
}
#Choice
if($DataTypes -eq "choice")
{
if($DatatypeOptions -eq "Dropdown")
{
#echo dropdown
#Dropdown
$dropdownfld=$fields.AddFieldAsXml("<Field Type='Choice' DisplayName='$ColumnName' Required='FALSE' Format='Dropdown'
FillInChoice='FALSE' Name='$ColumnInternalName'>
<Default>MyChoice1</Default>
<CHOICES>
<CHOICE>MyChoice1</CHOICE>
<CHOICE>MyChoice2</CHOICE>
</CHOICES>
</Field>",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Context.Load($fields)
$Context.Load($dropdownfld)
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: Choice field in Dropdown created successfully"
}
if($DatatypeOptions -eq "Radiobutton")
{
#echo "radio"
#Radiobutton
$radiobut=$fields.AddFieldAsXml("<Field Name='$ColumnInternalName' Type='Choice' DisplayName='$ColumnName' Format='RadioButtons'
FillInChoice='FALSE' >
<Default>MyChoice1</Default>
<CHOICES>
<CHOICE>MyChoice1</CHOICE>
<CHOICE>MyChoice2</CHOICE>
</CHOICES>
</Field>",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Context.Load($fields)
$Context.Load($radiobut)
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: Choice field in RadioButton created successfully"
}
if($DatatypeOptions -eq "Checkboxes")
{
#echo "Check"
#Checkboxes(allow multiple selection)
$checkbxfld=$fields.AddFieldAsXml("<Field Name='$ColumnInternalName' Type='MultiChoice' DisplayName='$ColumnName' FillInChoice='FALSE'>
<Default>MyChoice1</Default>
<CHOICES>
<CHOICE>MyChoice1</CHOICE>
<CHOICE>MyChoice2</CHOICE>
</CHOICES>
</Field>",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Context.Load($fields)
$Context.Load($checkbxfld)
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: Choice field in Checkbox created successfully"
}
}
if($DataTypes -eq "number")
{
#Number Field
$numfld=$fields.AddFieldAsXml("<Field Type='Number' DisplayName='$ColumnName' Required='FALSE' Name='$ColumnInternalName'/>",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Context.Load($fields)
$Context.Load($numfld)
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: Number field created successfully"
}
#Date&Time
if($DataTypes -eq "datetime")
{
if($DatatypeOptions -eq "Dateonly")
{
#DateOnly
$dateoly=$fields.AddFieldAsXml("<Field Type='DateTime' DisplayName='$ColumnName' Format='DateOnly' Name='$ColumnInternalName'/>",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Context.Load($fields)
$Context.Load($dateoly)
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: Date Only field created successfully"
}
if($DatatypeOptions -eq "Date&Time")
{
#DateandTime
$datetime=$fields.AddFieldAsXml("<Field Type='DateTime' DisplayName='$ColumnName' Format='DateTime' Name='$ColumnInternalName'/>",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Context.Load($fields)
$Context.Load($datetime)
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: Date and Time field created successfully"
}
}
if($DataTypes -eq "yesrno")
{
#Yes r No
$yrnfld=$fields.AddFieldAsXml("<Field Type='Boolean' DisplayName='$ColumnName' Name='$ColumnInternalName'>
<Default>1</Default>
</Field>",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Context.Load($fields)
$Context.Load($yrnfld)
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: Yes or No field created successfully"
}
if($DataTypes -eq "peoplergroup")
{
#People or Group
if($DatatypeOptions -eq "PeopleOnly")
{
#PeopleOnly
$peoponly=$fields.AddFieldAsXml("<Field Type='User' DisplayName='$ColumnName' List='UserInfo' ShowField='ImnName'
UserSelectionMode='PeopleOnly' UserSelectionScope='0' Name='$ColumnInternalName'/>",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Context.Load($fields)
$Context.Load($peoponly)
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: People Only field created successfully"
}
if($DatatypeOptions -eq "People&Group")
{
#People&Group
$peopgrp=$fields.AddFieldAsXml("<Field Type='User' DisplayName='$ColumnName' List='UserInfo' ShowField='ImnName'
UserSelectionMode='PeopleAndGroups' UserSelectionScope='0' Name='$ColumnInternalName'/>",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Context.Load($fields)
$Context.Load($peopgrp)
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: People and Group field created successfully"
}
}
if($DataTypes -eq "hyperlinkRpicture")
{
if($DatatypeOptions -eq "Hyperlink")
{
#Hyperlink
$hyperlnk=$fields.AddFieldAsXml("<Field Type='URL' DisplayName='$ColumnName' Format='Hyperlink' Name='$ColumnInternalName'/>",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Context.Load($fields)
$Context.Load($hyperlnk)
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: Hyperlink field created successfully"
}
if($DatatypeOptions -eq "Picture")
{
#Picture
$picturefld=$fields.AddFieldAsXml("<Field Type='URL' DisplayName='$ColumnName' Format='Image' Name='$ColumnInternalName'/>",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Context.Load($fields)
$Context.Load($picturefld)
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: Picture field created successfully"
}
}
if($LookupListNM -ne $null)
{
try{
$LookupLisNamecon = $Context.Web.Lists.GetByTitle($LookupListNM)
$Context.Load($LookupLisNamecon)
$Context.ExecuteQuery()
}
catch
{
}
if($DataTypes -eq "lookup")
{
try
{
$field = $fields.GetByInternalNameOrTitle($ColumnName)
$Context.Load($field)
$Context.ExecuteQuery()
Write-Host "Exception calling "ExecuteQuery" with "0" argument(s): "A duplicate field name "$ColumnName" was found."so create site column in different name" -ForegroundColor Red
}
catch
{
#Lookup
$castToMethodGeneric = [Microsoft.SharePoint.Client.ClientContext].GetMethod("CastTo")
$castToMethodLookup = $castToMethodGeneric.MakeGenericMethod([Microsoft.SharePoint.Client.FieldLookup])
#$internalName = "LookupWithStaticName"
$displayName = $ColumnName
$displayFieldForLookup = $LookupColumnNM
$newLookupField = $fields.AddFieldAsXml("<Field DisplayName='$ColumnInternalName' Type='Lookup' Mult='FALSE' />",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Context.Load($fields)
$Context.Load($newLookupField)
$lookupField = $castToMethodLookup.Invoke($Context, $newLookupField)
$lookupField.Title = $displayName
$lookupField.LookupList = $LookupLisNamecon.Id
$lookupField.LookupField = $displayFieldForLookup
$lookupField.Update()
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: Lookup field created successfully"
return
}
}
}
}
catch
{
Write-Host ($_.Exception.Message + "so create site column in different name") -ForegroundColor Red
}
}
function contenttypecreation([string]$ContentTypeNM, [string]$ContentGroupNM )
{
try{
# add a new content type - first, let's get all current ctypes
$web = $Context.Web
$contentTypes = $web.ContentTypes
$Context.Load($web)
$Context.Load($contentTypes)
$Context.ExecuteQuery()
# create a new content type object
$cType = New-Object Microsoft.SharePoint.Client.ContentTypeCreationInformation
$cType.Name = $ContentTypeNM
$cType.ParentContentType = $Context.Web.ContentTypes.GetById("0x01")
$cType.Group = $ContentGroupNM
$myCType = $contentTypes.Add($cType)
#$Context.ExecuteQuery()
$Context.Load($myCType)
$Context.ExecuteQuery()
Write-Host "Content Type " $ContentTypeNM " has been added to " $SiteURL
}
catch
{
Write-Host $_.Exception.Message "try to create the content type in different name" -ForegroundColor Red
}
}
function AddSiteColumnsToContentTypes([string]$ColumnName, [string]$ContentTypeNM)
{
try
{
#Check whether site column exists in site collection columns
try
{
$field = $fields.GetByInternalNameOrTitle($ColumnName)
$Context.Load($field)
$Context.ExecuteQuery()
#Write-Host "Site column" $ColumnName "exist" -ForegroundColor Cyan
}
catch
{
return
}
#Getting content types from the root site
$contentTypes = $Context.Site.RootWeb.ContentTypes
$Context.Load($contentTypes)
$Context.ExecuteQuery()
#Getting specified content type in which we need to add a column
$contentType = $contentTypes | Where {$_.Name -eq $ContentTypeNM}
#Get Fields from the content type
$fieldCollection = $contentType.Fields
$Context.Load($fieldCollection);
$Context.ExecuteQuery();
#Check if field already exists in content type or not
$IsFieldExists = $false
foreach($fld in $fieldCollection)
{
# Write-Host $fld.get_InternalName()
if($fld.get_InternalName() -eq $ColumnName){
$IsFieldExists = $true
}
}
if($IsFieldExists -eq $false)
{
#Get all the columns associated with content type
$fieldRefCollection = $contentType.FieldLinks;
$Context.Load($fieldRefCollection);
$Context.ExecuteQuery();
#Add a new column to the content type
Write-Host "Adding site column " $ColumnName "to the content type" -ForegroundColor Cyan
$fieldReferenceLink = New-Object Microsoft.SharePoint.Client.FieldLinkCreationInformation
$fieldReferenceLink.Field = $field;
$contentType.FieldLinks.Add($fieldReferenceLink);
$contentType.Update($true)
$Context.Load($contentType)
$Context.ExecuteQuery()
Write-Host "Field added successfully" -ForegroundColor Green
}
else
{
Write-Host "Site Column " $ColumnName " already exists in content type" -ForegroundColor Red
}
}
catch
{
Write-Host ("Error while adding field in contet type. Error -->> " + $_.Exception.Message ) -ForegroundColor Red
}
}
function CreatingList([string] $ListName)
{
try{
$ListInfo = New-Object Microsoft.SharePoint.Client.ListCreationInformation
$ListInfo.Title = $ListName
$ListInfo.TemplateType = "100"
$List = $Context.Web.Lists.Add($ListInfo)
$List.Description = $ListName
$List.Update()
$Context.ExecuteQuery()
Write-Host "List Name:" $ListName "created successfully"
}
catch{
Write-Host $_.Exception.Message -ForegroundColor Red
}
}
function AddingCTtoList([string] $ListName, [string] $ContentTypeNM)
{
try
{
#Getting content types from the root site
$contentTypes = $Context.Site.RootWeb.ContentTypes
$Context.Load($contentTypes)
$Context.ExecuteQuery()
#Getting specified content type in which we need to add a column
$contentType = $contentTypes | Where {$_.Name -eq $ContentTypeNM}
$CTID=$contentType.Id
#Load List
$Context.Load($Context.Web.Lists)
$Context.ExecuteQuery()
$contentType=$Context.Web.ContentTypes.GetById($CTID)
$Context.Load($contentType)
$contentType.Id
$ll=$Context.Web.Lists.GetByTitle($ListName)
$Context.load($ll)
$Context.load($ll.ContentTypes)
$Context.ExecuteQuery()
$ll.ContentTypesEnabled=$true
$AddedContentType=$ll.ContentTypes.AddExistingContentType($contentType)
$ll.Update()
$Context.ExecuteQuery()
Write-Host "Adding content type " $contentType.Name " to " $ll.Title
}
catch
{
Write-Host "This content type already exists, "$_.Exception.Message "so choose another content type" -ForegroundColor Red
}
}
function ReorderContentTypesInList()
{
param(
[Parameter(Mandatory=$true)][string]$listName,
[Parameter(Mandatory=$true)][string]$ContentTypeNM
)
begin{
try
{
$ContentTypeNamesInOrder= $ContentTypeNM
#Retrieve List
#
$list = $Context.Web.Lists.GetByTitle($listName)
$Context.Load($list)
$Context.ExecuteQuery()
#Get Content Types from a list
#
$contentTypes = $list.ContentTypes
$Context.Load($contentTypes)
$Context.ExecuteQuery()
# Write-Host $contentTypes.Name
}
catch{
Write-Host "Error while getting context. Error -->> " + $_.Exception.Message -ForegroundColor Red
}
}
process{
try
{
#Making generic list of content type ids in passed order
#
$ctList = New-Object System.Collections.Generic.List[Microsoft.SharePoint.Client.ContentTypeId]
Foreach($ct in $ContentTypeNamesInOrder){
$ctToInclude = $contentTypes | Where {$_.Name -eq $ct}
$ctList.Add($ctToInclude.Id)
}
#Updating content type order
#
$list.RootFolder.UniqueContentTypeOrder = $ctList
$list.Update()
$Context.Load($list)
$Context.ExecuteQuery()
Write-Host "Content Type is set to default successfully!!!" -ForegroundColor Green
}
catch
{
Write-Host ("Error while reordering content types in a list. Error -->> " + $_.Exception.Message) -ForegroundColor Red
}
}
end{
$Context.Dispose()
}
}
################### End of Functions ###############################################
#Add references to SharePoint client assemblies and authenticate to Office 365 site - required for CSOM
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
Add-Type -Path "c:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Taxonomy.dll"
$question = Read-Host "Are you proceed with On-Premises or Office365? If On-Premises Type ON Else Type OFF for Office365"
If (($question -eq "ON") -or ($question -eq "on") -or ($question -eq "On") -or ($question -eq "oN"))
{
$SiteURL = Read-Host -Prompt "Please enter the Site URL"
$CSVFileName=Read-Host -Prompt "Please enter Your CSV file Name"
#Bind to site collection
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
if (!$Context.ServerObjectIsNull.Value)
{
Write-Host "Connected to SharePoint On-Premises site: '$siteUrl'" -ForegroundColor Green
$web = $Context.Web
$Context.Load($web)
$Context.ExecuteQuery()
}
# retrieve all site columns (fields)
$web = $Context.Web
$fields = $web.Fields
$Context.Load($web)
$Context.Load($fields)
$Context.ExecuteQuery()
}
Elseif (($question -eq "OFF") -or ($question -eq "off") -or ($question -eq "Off") -or ($question -eq "oFF"))
{
$User = Read-Host -Prompt "Please enter your Login Name"
$Password = Read-Host -Prompt "Please enter your password" -AsSecureString
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User,$Password)
$SiteURL = Read-Host -Prompt "Please enter the Site URL"
$CSVFileName=Read-Host -Prompt "Please enter Your CSV file Name"
#Bind to site collection
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User,$Password)
$Context.Credentials = $Creds
if (!$Context.ServerObjectIsNull.Value)
{
Write-Host "Connected to SharePoint Online site: '$siteUrl'" -ForegroundColor Green
$web = $Context.Web
$Context.Load($web)
$Context.ExecuteQuery()
}
# retrieve all site columns (fields)
$web = $Context.Web
$fields = $web.Fields
$Context.Load($web)
$Context.Load($fields)
$Context.ExecuteQuery()
}
Else
{
Write-Host -BackgroundColor White -ForegroundColor Red "INVALID ENTRY! Please try again."
Break
#Exit
}
#################Creating Site columns##########################################################
$SiteColumnCreationDetailsCSV = $scriptBase + "\" + $CSVFileName
import-csv $SiteColumnCreationDetailsCSV | where {
CreateField $_.ColumnName $_.ColumnInternalName $_.DataTypes $_.DatatypeOptions $_.LookupListNM $_.LookupColumnNM
}
#################Creating Content Type#########################################################
$contenttypeCreationCSV = $scriptBase + "\" + $CSVFileName
import-csv $contenttypeCreationCSV |select -first 1 | where {
if(($_.ContentTypeNM -ne $null) -and ($_.ContentGroupNM -ne $null))
{
contenttypecreation $_.ContentTypeNM $_.ContentGroupNM
}
}
#################Adding site column to content type#############################################
$SiteColumnReferencedContentTypesCSV = $scriptBase + "\" + $CSVFileName
import-csv $SiteColumnReferencedContentTypesCSV | where {
AddSiteColumnsToContentTypes $_.ColumnName $_.ContentTypeNM
}
###################Creating List##################################
$creatinglistCSV = $scriptBase + "\" + $CSVFileName
import-csv $creatinglistCSV |select -first 1 | where {
CreatingList $_.ListName
}
#################Adding Content Type to List#####################
$addingCTtolistCSV = $scriptBase + "\" + $CSVFileName
import-csv $addingCTtolistCSV |select -first 1 | where {
AddingCTtoList $_.ListName $_.ContentTypeNM
}
#################Reordering Content Type in the List#####################
$reorderingCTinlistCSV = $scriptBase + "\" + $CSVFileName
import-csv $reorderingCTinlistCSV |select -first 1 | where {
ReorderContentTypesInList $_.ListName $_.ContentTypeNM
}
Sample CSV:
if ( (Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null )
{
Add-PSSnapin Microsoft.SharePoint.Powershell
}
########################### End of Add SharePoint PowerShell Snapin ##################################
######################## Set Execution Path ################################################
$scriptBase = split-path $SCRIPT:MyInvocation.MyCommand.Path -parent
Set-Location $scriptBase
################################# End of Set Execution Path #################################
################################# Functions #####################################################
#$myCType = $null
function CreateField([string]$ColumnName, [string] $ColumnInternalName, [string] $DataTypes, [string] $DatatypeOptions, [string] $LookupListNM, [string] $LookupColumnNM)
{
try{
if($DataTypes-eq "singleline")
{
#SingleLine
$singleline=$fields.AddFieldAsXml("<Field Type='Text' DisplayName='$ColumnName' Required='False' MaxLength='255' Name='$ColumnInternalName' />",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Context.Load($fields)
$Context.Load($singleline)
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: SingleLine of Text field created successfully"
}
if($DataTypes-eq "multipleline")
{
#MulipleLine
if($DatatypeOptions -eq "plaintext")
{
#PlainText
$plaintxt=$fields.AddFieldAsXml("<Field Type='Note' DisplayName='$ColumnName' Required='FALSE' NumLines='6' RichText='FALSE'
Sortable='FALSE' Name='$ColumnInternalName'/>",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Context.Load($fields)
$Context.Load($plaintxt)
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: MultiLine of Plain Text field created successfully"
}
if($DatatypeOptions -eq "richtext")
{
#RichText
$richtxt=$fields.AddFieldAsXml("<Field Type='Note' DisplayName='$ColumnName' Required='FALSE' NumLines='6'
RichText='TRUE' RichTextMode='Compatible' Sortable='FALSE' Name='$ColumnInternalName' />",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Context.Load($fields)
$Context.Load($richtxt)
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: MultiLine of Rich Text field created successfully"
}
if($DatatypeOptions -eq "enhancedrichtext")
{
#EnhancedRichText
$enhancetxt=$fields.AddFieldAsXml("<Field Type='Note' DisplayName='$ColumnName' Required='FALSE' NumLines='6' RichText='TRUE'
RichTextMode='FullHtml' IsolateStyles='TRUE' Sortable='FALSE' Name='$ColumnInternalName' />",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Context.Load($fields)
$Context.Load($enhancetxt)
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: MultiLine of EnhancedRich Text field created successfully"
}
}
#Choice
if($DataTypes -eq "choice")
{
if($DatatypeOptions -eq "Dropdown")
{
#echo dropdown
#Dropdown
$dropdownfld=$fields.AddFieldAsXml("<Field Type='Choice' DisplayName='$ColumnName' Required='FALSE' Format='Dropdown'
FillInChoice='FALSE' Name='$ColumnInternalName'>
<Default>MyChoice1</Default>
<CHOICES>
<CHOICE>MyChoice1</CHOICE>
<CHOICE>MyChoice2</CHOICE>
</CHOICES>
</Field>",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Context.Load($fields)
$Context.Load($dropdownfld)
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: Choice field in Dropdown created successfully"
}
if($DatatypeOptions -eq "Radiobutton")
{
#echo "radio"
#Radiobutton
$radiobut=$fields.AddFieldAsXml("<Field Name='$ColumnInternalName' Type='Choice' DisplayName='$ColumnName' Format='RadioButtons'
FillInChoice='FALSE' >
<Default>MyChoice1</Default>
<CHOICES>
<CHOICE>MyChoice1</CHOICE>
<CHOICE>MyChoice2</CHOICE>
</CHOICES>
</Field>",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Context.Load($fields)
$Context.Load($radiobut)
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: Choice field in RadioButton created successfully"
}
if($DatatypeOptions -eq "Checkboxes")
{
#echo "Check"
#Checkboxes(allow multiple selection)
$checkbxfld=$fields.AddFieldAsXml("<Field Name='$ColumnInternalName' Type='MultiChoice' DisplayName='$ColumnName' FillInChoice='FALSE'>
<Default>MyChoice1</Default>
<CHOICES>
<CHOICE>MyChoice1</CHOICE>
<CHOICE>MyChoice2</CHOICE>
</CHOICES>
</Field>",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Context.Load($fields)
$Context.Load($checkbxfld)
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: Choice field in Checkbox created successfully"
}
}
if($DataTypes -eq "number")
{
#Number Field
$numfld=$fields.AddFieldAsXml("<Field Type='Number' DisplayName='$ColumnName' Required='FALSE' Name='$ColumnInternalName'/>",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Context.Load($fields)
$Context.Load($numfld)
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: Number field created successfully"
}
#Date&Time
if($DataTypes -eq "datetime")
{
if($DatatypeOptions -eq "Dateonly")
{
#DateOnly
$dateoly=$fields.AddFieldAsXml("<Field Type='DateTime' DisplayName='$ColumnName' Format='DateOnly' Name='$ColumnInternalName'/>",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Context.Load($fields)
$Context.Load($dateoly)
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: Date Only field created successfully"
}
if($DatatypeOptions -eq "Date&Time")
{
#DateandTime
$datetime=$fields.AddFieldAsXml("<Field Type='DateTime' DisplayName='$ColumnName' Format='DateTime' Name='$ColumnInternalName'/>",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Context.Load($fields)
$Context.Load($datetime)
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: Date and Time field created successfully"
}
}
if($DataTypes -eq "yesrno")
{
#Yes r No
$yrnfld=$fields.AddFieldAsXml("<Field Type='Boolean' DisplayName='$ColumnName' Name='$ColumnInternalName'>
<Default>1</Default>
</Field>",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Context.Load($fields)
$Context.Load($yrnfld)
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: Yes or No field created successfully"
}
if($DataTypes -eq "peoplergroup")
{
#People or Group
if($DatatypeOptions -eq "PeopleOnly")
{
#PeopleOnly
$peoponly=$fields.AddFieldAsXml("<Field Type='User' DisplayName='$ColumnName' List='UserInfo' ShowField='ImnName'
UserSelectionMode='PeopleOnly' UserSelectionScope='0' Name='$ColumnInternalName'/>",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Context.Load($fields)
$Context.Load($peoponly)
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: People Only field created successfully"
}
if($DatatypeOptions -eq "People&Group")
{
#People&Group
$peopgrp=$fields.AddFieldAsXml("<Field Type='User' DisplayName='$ColumnName' List='UserInfo' ShowField='ImnName'
UserSelectionMode='PeopleAndGroups' UserSelectionScope='0' Name='$ColumnInternalName'/>",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Context.Load($fields)
$Context.Load($peopgrp)
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: People and Group field created successfully"
}
}
if($DataTypes -eq "hyperlinkRpicture")
{
if($DatatypeOptions -eq "Hyperlink")
{
#Hyperlink
$hyperlnk=$fields.AddFieldAsXml("<Field Type='URL' DisplayName='$ColumnName' Format='Hyperlink' Name='$ColumnInternalName'/>",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Context.Load($fields)
$Context.Load($hyperlnk)
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: Hyperlink field created successfully"
}
if($DatatypeOptions -eq "Picture")
{
#Picture
$picturefld=$fields.AddFieldAsXml("<Field Type='URL' DisplayName='$ColumnName' Format='Image' Name='$ColumnInternalName'/>",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Context.Load($fields)
$Context.Load($picturefld)
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: Picture field created successfully"
}
}
if($LookupListNM -ne $null)
{
try{
$LookupLisNamecon = $Context.Web.Lists.GetByTitle($LookupListNM)
$Context.Load($LookupLisNamecon)
$Context.ExecuteQuery()
}
catch
{
}
if($DataTypes -eq "lookup")
{
try
{
$field = $fields.GetByInternalNameOrTitle($ColumnName)
$Context.Load($field)
$Context.ExecuteQuery()
Write-Host "Exception calling "ExecuteQuery" with "0" argument(s): "A duplicate field name "$ColumnName" was found."so create site column in different name" -ForegroundColor Red
}
catch
{
#Lookup
$castToMethodGeneric = [Microsoft.SharePoint.Client.ClientContext].GetMethod("CastTo")
$castToMethodLookup = $castToMethodGeneric.MakeGenericMethod([Microsoft.SharePoint.Client.FieldLookup])
#$internalName = "LookupWithStaticName"
$displayName = $ColumnName
$displayFieldForLookup = $LookupColumnNM
$newLookupField = $fields.AddFieldAsXml("<Field DisplayName='$ColumnInternalName' Type='Lookup' Mult='FALSE' />",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Context.Load($fields)
$Context.Load($newLookupField)
$lookupField = $castToMethodLookup.Invoke($Context, $newLookupField)
$lookupField.Title = $displayName
$lookupField.LookupList = $LookupLisNamecon.Id
$lookupField.LookupField = $displayFieldForLookup
$lookupField.Update()
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: Lookup field created successfully"
return
}
}
}
}
catch
{
Write-Host ($_.Exception.Message + "so create site column in different name") -ForegroundColor Red
}
}
function contenttypecreation([string]$ContentTypeNM, [string]$ContentGroupNM )
{
try{
# add a new content type - first, let's get all current ctypes
$web = $Context.Web
$contentTypes = $web.ContentTypes
$Context.Load($web)
$Context.Load($contentTypes)
$Context.ExecuteQuery()
# create a new content type object
$cType = New-Object Microsoft.SharePoint.Client.ContentTypeCreationInformation
$cType.Name = $ContentTypeNM
$cType.ParentContentType = $Context.Web.ContentTypes.GetById("0x01")
$cType.Group = $ContentGroupNM
$myCType = $contentTypes.Add($cType)
#$Context.ExecuteQuery()
$Context.Load($myCType)
$Context.ExecuteQuery()
Write-Host "Content Type " $ContentTypeNM " has been added to " $SiteURL
}
catch
{
Write-Host $_.Exception.Message "try to create the content type in different name" -ForegroundColor Red
}
}
function AddSiteColumnsToContentTypes([string]$ColumnName, [string]$ContentTypeNM)
{
try
{
#Check whether site column exists in site collection columns
try
{
$field = $fields.GetByInternalNameOrTitle($ColumnName)
$Context.Load($field)
$Context.ExecuteQuery()
#Write-Host "Site column" $ColumnName "exist" -ForegroundColor Cyan
}
catch
{
return
}
#Getting content types from the root site
$contentTypes = $Context.Site.RootWeb.ContentTypes
$Context.Load($contentTypes)
$Context.ExecuteQuery()
#Getting specified content type in which we need to add a column
$contentType = $contentTypes | Where {$_.Name -eq $ContentTypeNM}
#Get Fields from the content type
$fieldCollection = $contentType.Fields
$Context.Load($fieldCollection);
$Context.ExecuteQuery();
#Check if field already exists in content type or not
$IsFieldExists = $false
foreach($fld in $fieldCollection)
{
# Write-Host $fld.get_InternalName()
if($fld.get_InternalName() -eq $ColumnName){
$IsFieldExists = $true
}
}
if($IsFieldExists -eq $false)
{
#Get all the columns associated with content type
$fieldRefCollection = $contentType.FieldLinks;
$Context.Load($fieldRefCollection);
$Context.ExecuteQuery();
#Add a new column to the content type
Write-Host "Adding site column " $ColumnName "to the content type" -ForegroundColor Cyan
$fieldReferenceLink = New-Object Microsoft.SharePoint.Client.FieldLinkCreationInformation
$fieldReferenceLink.Field = $field;
$contentType.FieldLinks.Add($fieldReferenceLink);
$contentType.Update($true)
$Context.Load($contentType)
$Context.ExecuteQuery()
Write-Host "Field added successfully" -ForegroundColor Green
}
else
{
Write-Host "Site Column " $ColumnName " already exists in content type" -ForegroundColor Red
}
}
catch
{
Write-Host ("Error while adding field in contet type. Error -->> " + $_.Exception.Message ) -ForegroundColor Red
}
}
function CreatingList([string] $ListName)
{
try{
$ListInfo = New-Object Microsoft.SharePoint.Client.ListCreationInformation
$ListInfo.Title = $ListName
$ListInfo.TemplateType = "100"
$List = $Context.Web.Lists.Add($ListInfo)
$List.Description = $ListName
$List.Update()
$Context.ExecuteQuery()
Write-Host "List Name:" $ListName "created successfully"
}
catch{
Write-Host $_.Exception.Message -ForegroundColor Red
}
}
function AddingCTtoList([string] $ListName, [string] $ContentTypeNM)
{
try
{
#Getting content types from the root site
$contentTypes = $Context.Site.RootWeb.ContentTypes
$Context.Load($contentTypes)
$Context.ExecuteQuery()
#Getting specified content type in which we need to add a column
$contentType = $contentTypes | Where {$_.Name -eq $ContentTypeNM}
$CTID=$contentType.Id
#Load List
$Context.Load($Context.Web.Lists)
$Context.ExecuteQuery()
$contentType=$Context.Web.ContentTypes.GetById($CTID)
$Context.Load($contentType)
$contentType.Id
$ll=$Context.Web.Lists.GetByTitle($ListName)
$Context.load($ll)
$Context.load($ll.ContentTypes)
$Context.ExecuteQuery()
$ll.ContentTypesEnabled=$true
$AddedContentType=$ll.ContentTypes.AddExistingContentType($contentType)
$ll.Update()
$Context.ExecuteQuery()
Write-Host "Adding content type " $contentType.Name " to " $ll.Title
}
catch
{
Write-Host "This content type already exists, "$_.Exception.Message "so choose another content type" -ForegroundColor Red
}
}
function ReorderContentTypesInList()
{
param(
[Parameter(Mandatory=$true)][string]$listName,
[Parameter(Mandatory=$true)][string]$ContentTypeNM
)
begin{
try
{
$ContentTypeNamesInOrder= $ContentTypeNM
#Retrieve List
#
$list = $Context.Web.Lists.GetByTitle($listName)
$Context.Load($list)
$Context.ExecuteQuery()
#Get Content Types from a list
#
$contentTypes = $list.ContentTypes
$Context.Load($contentTypes)
$Context.ExecuteQuery()
# Write-Host $contentTypes.Name
}
catch{
Write-Host "Error while getting context. Error -->> " + $_.Exception.Message -ForegroundColor Red
}
}
process{
try
{
#Making generic list of content type ids in passed order
#
$ctList = New-Object System.Collections.Generic.List[Microsoft.SharePoint.Client.ContentTypeId]
Foreach($ct in $ContentTypeNamesInOrder){
$ctToInclude = $contentTypes | Where {$_.Name -eq $ct}
$ctList.Add($ctToInclude.Id)
}
#Updating content type order
#
$list.RootFolder.UniqueContentTypeOrder = $ctList
$list.Update()
$Context.Load($list)
$Context.ExecuteQuery()
Write-Host "Content Type is set to default successfully!!!" -ForegroundColor Green
}
catch
{
Write-Host ("Error while reordering content types in a list. Error -->> " + $_.Exception.Message) -ForegroundColor Red
}
}
end{
$Context.Dispose()
}
}
################### End of Functions ###############################################
#Add references to SharePoint client assemblies and authenticate to Office 365 site - required for CSOM
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
Add-Type -Path "c:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Taxonomy.dll"
$question = Read-Host "Are you proceed with On-Premises or Office365? If On-Premises Type ON Else Type OFF for Office365"
If (($question -eq "ON") -or ($question -eq "on") -or ($question -eq "On") -or ($question -eq "oN"))
{
$SiteURL = Read-Host -Prompt "Please enter the Site URL"
$CSVFileName=Read-Host -Prompt "Please enter Your CSV file Name"
#Bind to site collection
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
if (!$Context.ServerObjectIsNull.Value)
{
Write-Host "Connected to SharePoint On-Premises site: '$siteUrl'" -ForegroundColor Green
$web = $Context.Web
$Context.Load($web)
$Context.ExecuteQuery()
}
# retrieve all site columns (fields)
$web = $Context.Web
$fields = $web.Fields
$Context.Load($web)
$Context.Load($fields)
$Context.ExecuteQuery()
}
Elseif (($question -eq "OFF") -or ($question -eq "off") -or ($question -eq "Off") -or ($question -eq "oFF"))
{
$User = Read-Host -Prompt "Please enter your Login Name"
$Password = Read-Host -Prompt "Please enter your password" -AsSecureString
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User,$Password)
$SiteURL = Read-Host -Prompt "Please enter the Site URL"
$CSVFileName=Read-Host -Prompt "Please enter Your CSV file Name"
#Bind to site collection
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User,$Password)
$Context.Credentials = $Creds
if (!$Context.ServerObjectIsNull.Value)
{
Write-Host "Connected to SharePoint Online site: '$siteUrl'" -ForegroundColor Green
$web = $Context.Web
$Context.Load($web)
$Context.ExecuteQuery()
}
# retrieve all site columns (fields)
$web = $Context.Web
$fields = $web.Fields
$Context.Load($web)
$Context.Load($fields)
$Context.ExecuteQuery()
}
Else
{
Write-Host -BackgroundColor White -ForegroundColor Red "INVALID ENTRY! Please try again."
Break
#Exit
}
#################Creating Site columns##########################################################
$SiteColumnCreationDetailsCSV = $scriptBase + "\" + $CSVFileName
import-csv $SiteColumnCreationDetailsCSV | where {
CreateField $_.ColumnName $_.ColumnInternalName $_.DataTypes $_.DatatypeOptions $_.LookupListNM $_.LookupColumnNM
}
#################Creating Content Type#########################################################
$contenttypeCreationCSV = $scriptBase + "\" + $CSVFileName
import-csv $contenttypeCreationCSV |select -first 1 | where {
if(($_.ContentTypeNM -ne $null) -and ($_.ContentGroupNM -ne $null))
{
contenttypecreation $_.ContentTypeNM $_.ContentGroupNM
}
}
#################Adding site column to content type#############################################
$SiteColumnReferencedContentTypesCSV = $scriptBase + "\" + $CSVFileName
import-csv $SiteColumnReferencedContentTypesCSV | where {
AddSiteColumnsToContentTypes $_.ColumnName $_.ContentTypeNM
}
###################Creating List##################################
$creatinglistCSV = $scriptBase + "\" + $CSVFileName
import-csv $creatinglistCSV |select -first 1 | where {
CreatingList $_.ListName
}
#################Adding Content Type to List#####################
$addingCTtolistCSV = $scriptBase + "\" + $CSVFileName
import-csv $addingCTtolistCSV |select -first 1 | where {
AddingCTtoList $_.ListName $_.ContentTypeNM
}
#################Reordering Content Type in the List#####################
$reorderingCTinlistCSV = $scriptBase + "\" + $CSVFileName
import-csv $reorderingCTinlistCSV |select -first 1 | where {
ReorderContentTypesInList $_.ListName $_.ContentTypeNM
}
Sample CSV:
No comments:
Post a Comment