Introduction
In this blog we will about to add a column to a specific view in a specific list in multiple webs in SharePoint 2013 using PowerShell method. The list exists in every sub web. The view exists in every list. There are hundreds of sub webs that I need to traverse through and it will take time.
So for that I have created a small PowerShell script to work on this.
Steps
- Start your windows PowerShell on your computer.
- Right click and select Run as administrator option.
- Paste the below script on the PowerShell window and click the enter button.
- Check your SharePoint site page will be created successfully.
- # -------------------------------------------------------------------------
- # PURPOSE: ADD A COLUMN TO A SPECIFIED VIEW IN A SPECIFIED LIST IN MULTIPLE WEBS WITHIN A SITE COLLECTION.
- # PARAMETERS: 1. SITE COLLECTION URL; 2. COLUMNNAME; 3. LISTNAME; 4. VIEWNAME
- # -------------------------------------------------------------------------
-
- function Add-ColumnToView
- {
- Param(
- [Parameter(Mandatory=$true)]
- [string]$Url,
- [Parameter(Mandatory=$true)]
- [string]$ColumnName,
- [Parameter(Mandatory=$true)]
- [string]$ListName,
- [Parameter(Mandatory=$true)]
- [string]$ViewName
- ) # END PARAMS
-
- if ($Url)
- {
- $site = Get-SPSite $Url
-
- if ($site)
- {
- # GET THE SUB WEBS IN SITE COLLECTION
- $allWebs = $site.allwebs
-
- # LOOP THROUGH EACH SUB WEB
- foreach ($spweb in $allWebs)
- {
- try
- {
- # FIND THE LIST MATCHING THE $LISTNAME
- $list = $spweb.GetList($spweb.Url + "/Lists/" + $ListName)
-
- # CHECK IF THE LIST OBJECT EXISTS
- if ($list)
- {
- # GET THE SPECIFIC VIEW
- $view = $list.Views[$ViewName]
-
- # CHECK IF THE VIEW OBJECT EXISTS
- if($view)
- {
- # DELETE IF ALREADY EXIST
- while($view.ViewFields.ToStringCollection().Contains($ColumnName))
- {
- write-host (" Deleting Column From: " + $spweb.Url) -foregroundcolor yellow
- $view.ViewFields.delete($ColumnName)
- $view.Update()
- }
-
- # ADD COLUMN
- if(!$view.ViewFields.ToStringCollection().Contains($ColumnName))
- {
- write-host (" Adding Column To: " + $spweb.Url) -foregroundcolor green
- $view.ViewFields.add($ColumnName)
- $view.Update()
- }
- }
- }
- }
- catch [Exception]
- {
- write-host (" Error: " + $_.Exception.ToString()) -foregroundcolor red
- }
- }
- }
- else
- {
- write-host (" Error: " + "Site Collection Not available") -foregroundcolor white
- }
- $site.Dispose()
- }
- else
- {
- write-host (" Error: " + "Site Collection URL Not Specified.") -foregroundcolor white
- }
- } #END FUNCTION
Run the script with the required administrator privilege.
To verify that, go the Pages List in particular and make sure that available or not.