I'm hoping that someone can give me a hand with two issues in Powershell that I have with modifying views in SharePoint 2010. I've had some help on this from someone over at stackoverflow but hasn't been able to progress further on two follow-up questions on the script.
They are hopefully quite simple to solve, just beyond my meagre grasp of powershell.
The goal of the script is to: Loop through all Document Libraries in a Web Application, check if there is a view already defined called "Detailed" and if not then create that view.
Issue 1) The script is generating an error when it runs. It was mentioned that you can't modify an element of the collection that is being enumerated. Can you show me how to work around this? Despite changes being made to avoid the problem it's still happening
An error occurred while enumerating through a collection: Collection was modified; enumera tion operation may not execute.. At C:\Users\quickdev1\Documents\LoopThroughAl lLibrariesCreateView.ps1:7 char:10
+ foreach <<<< ($list in $web.Lists) {
+ CategoryInfo : InvalidOperati on: (Microsoft.Share...on+SPEnumerator:S PEnumerator) [], RuntimeException
+ FullyQualifiedErrorId : BadEnumeration
Issue 2) I would like to put in some logic to check if an existing view is already there with the name "Detailed" and if so to skip that Library but I'm not sure how to achieve it.
Any assistance on these two items would be greatly appreciated.
Thanks,
Ashley
Add-PSSnapin Microsoft.SharePoint.PowerShell -erroraction SilentlyContinue
$siteURL = "http://sp14fdev01/"
$site = Get-SPSite($siteURL)
foreach($web in $site.AllWebs) {
foreach($list in $web.Lists) {
if($list.BaseType -eq "DocumentLibrary") {
// the variables `$web` and `$list` already reference the objects you need
//$site = New-Object Microsoft.SharePoint.SPSite($SiteURL) ;
//$web = $site.OpenWeb($SiteURL);
// new instance of the list is necessary to avoid the error "Collection was modified"
$newList = $web.Lists.item($list.ID);
$viewfields = New-Object System.Collections.Specialized.StringCollection
$viewfields.Add("DocIcon")
$viewfields.Add("LinkFilename")
$viewfields.Add("_UIVersionString")
$viewfields.Add("FileSizeDisplay")
$viewfields.Add("Created")
$viewfields.Add("Modified")
$viewfields.Add("Editor")
[void]$newList.Views.Add("Detailed", $viewfields, "", 100, $true, $true)
$newList.Update();
// setting the default view
$view=$newList.Views["Detailed"]
$view.DefaultView = $true
$view.Update()
}
}
$web.Dispose();
}
$site.Dispose();