Friday, 28 July 2017

Add new Column to List in SharePoint Online using Power Shell script

cls
#Specify tenant admin and site URL
$User = "sravankumar1107@vayugundla.onmicrosoft.com"
$SiteURL = "https://vayugundla.sharepoint.com/"

#Add references to SharePoint client assemblies and authenticate to Office 365 site - required for CSOM
Add-Type -Path "D:\SharePointDLL\Microsoft.SharePoint.Client.dll"
Add-Type -Path "D:\SharePointDLL\Microsoft.SharePoint.Client.Runtime.dll"
$Password = Read-Host -Prompt "Please enter your password" -AsSecureString
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User,$Password)

#Bind to site collection
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User,$Password)
$Context.Credentials = $Creds
#Retrieve lists
$Lists = $Context.Web.Lists
$Context.Load($Lists)
$Context.ExecuteQuery()
write-host "Completed the loading of lists"
foreach ($list in $Lists) {
if ($list.BaseType -eq "DocumentLibrary") {
write-host "Currently adding the column to" $list.Title
#Adding new column to the Library
$List.Fields.AddFieldAsXml("<Field Type='Text' Required='false' Name='Quotes' MaxLength='255' DisplayName='Quotes'/>",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$List.Update()
$Context.ExecuteQuery()
#update an item to the list
$listitems = $List.GetItems([Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery())
$context.load($listitems)
$Context.ExecuteQuery()
foreach($item in $listitems)
{
$item["Quotes"] = "Test"
$item.Update()
$Context.ExecuteQuery()
write-host "Updated the Quotes Column"
}
}
}
write-host "Added a new column and updated the coulumn to the all libraries"