Tuesday, March 12, 2013

SharePoint PowerShell Create View Based on Existing View

The following PowerShell script crawls the specified lists, copies the fields from the All Items views and creates a new view named "Created By Me" and sets it as default. Tested with SharePoint 2010 but should work with 2013 as well. Tested with list but not with Document Libraries.

I used this script as a base.


$ver = $host | select version
if ($ver.Version.Major -gt 1) {$host.Runspace.ThreadOptions = "ReuseThread"} 
if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null) 
{
 Add-PSSnapin "Microsoft.SharePoint.PowerShell"
}

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint") 

$web = Get-SPWeb -Identity "http://portal/sites/Requests"
$lists=$web.Lists["User Request", "Hardware Request",  "Employee Request"]
$SourceView="All Items"
$NewViewName="Created By Me"
$NewViewDefault=$true


foreach($list in $lists) {

 $view = $list.Views[$SourceView]
 $Viewfields = $list.Views[$SourceView].ViewFields.ToStringCollection()
 $viewRowLimit="100"
 $viewPaged=$true
 $viewDefaultView=$NewViewDefault

# Setting the Query for the View
 $viewQuery = ""
 $viewName = $NewViewName

# Finally – Provisioning the View
 $myListView = $list.Views.Add($viewName, $viewFields, $viewQuery, 100, $True, $False, "HTML", $False)

# You need to Update the View for changes made to the view
# Updating the List is not enough
 $myListView.DefaultView = $True
 $myListView.Update()
 $list.Update()
}

$web.Dispose()