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

  1. Start your windows PowerShell on your computer.
  2. Right click and select Run as administrator option.
  3. Paste the below script on the PowerShell window and click the enter button.
  4. Check your SharePoint site page will be created successfully.
  1. # -------------------------------------------------------------------------
  2. # PURPOSE: ADD A COLUMN TO A SPECIFIED VIEW IN A SPECIFIED LIST IN MULTIPLE WEBS WITHIN A SITE COLLECTION.
  3. # PARAMETERS: 1. SITE COLLECTION URL; 2. COLUMNNAME; 3. LISTNAME; 4. VIEWNAME
  4. # -------------------------------------------------------------------------
  5. function Add-ColumnToView
  6. {
  7. Param(
  8. [Parameter(Mandatory=$true)]
  9. [string]$Url,
  10. [Parameter(Mandatory=$true)]
  11. [string]$ColumnName,
  12. [Parameter(Mandatory=$true)]
  13. [string]$ListName,
  14. [Parameter(Mandatory=$true)]
  15. [string]$ViewName
  16. ) # END PARAMS
  17. if ($Url)
  18. {
  19. $site = Get-SPSite $Url
  20. if ($site)
  21. {
  22. # GET THE SUB WEBS IN SITE COLLECTION
  23. $allWebs = $site.allwebs
  24. # LOOP THROUGH EACH SUB WEB
  25. foreach ($spweb in $allWebs)
  26. {
  27. try
  28. {
  29. # FIND THE LIST MATCHING THE $LISTNAME
  30. $list = $spweb.GetList($spweb.Url + "/Lists/" + $ListName)
  31. # CHECK IF THE LIST OBJECT EXISTS
  32. if ($list)
  33. {
  34. # GET THE SPECIFIC VIEW
  35. $view = $list.Views[$ViewName]
  36. # CHECK IF THE VIEW OBJECT EXISTS
  37. if($view)
  38. {
  39. # DELETE IF ALREADY EXIST
  40. while($view.ViewFields.ToStringCollection().Contains($ColumnName))
  41. {
  42. write-host (" Deleting Column From: " + $spweb.Url) -foregroundcolor yellow
  43. $view.ViewFields.delete($ColumnName)
  44. $view.Update()
  45. }
  46. # ADD COLUMN
  47. if(!$view.ViewFields.ToStringCollection().Contains($ColumnName))
  48. {
  49. write-host (" Adding Column To: " + $spweb.Url) -foregroundcolor green
  50. $view.ViewFields.add($ColumnName)
  51. $view.Update()
  52. }
  53. }
  54. }
  55. }
  56. catch [Exception]
  57. {
  58. write-host (" Error: " + $_.Exception.ToString()) -foregroundcolor red
  59. }
  60. }
  61. }
  62. else
  63. {
  64. write-host (" Error: " + "Site Collection Not available") -foregroundcolor white
  65. }
  66. $site.Dispose()
  67. }
  68. else
  69. {
  70. write-host (" Error: " + "Site Collection URL Not Specified.") -foregroundcolor white
  71. }
  72. } #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.