I have created the below powershell to loop through all my PWA sites and create a new view. The script checks if the view already exists and then it checks if the new view has been set to the default view, if the new view is the default, it amends the default back to the first ([0]) view in the views array.
I am receiving the "enumerating through a collection" error as I understand you cant edit the current collection, I am quite new to powershell and having looked at answers I dont fully understand how I can amend the code to prevent this error, can anyone help please?
The error occurs when it tries to update the defaultview within the defaultViewCheck function:
function defaultViewCheck
{
Param ($dvweb, $dvlist)
#Check SSIS Package default
$newList = $dvweb.Lists.item($dvlist.ID)
$viewCheck = $newList.Views["SSIS Package View - Do not Touch"]
if ($viewCheck.DefaultView = $true)
{
write-host $viewCheck "is set to default"
# set value 0 in the list array to the default view
$defaultView = $dvlist.Views[0]
## Set the default View $view = $newList.Views[$defaultView]
$view.DefaultView = $true
$view.Update()
write-host $defaultView "Set to default view" -foregroundcolor "blue"
Return
}
else
{
write-host "Set Default - No action required" -foregroundcolor "yellow"
Return
}
}
$siteURL = "[URL]"
$strViewName = "SSIS Package View - Do not Touch"
$ListNames = @("Change Requests", "Issues", "Risks", "Actions", "Status Summary", "Benefits", "Lessons Learned")
# create a new SPsite object and recursively go through all webs
$site = new-object Microsoft.SharePoint.SPSite($siteURL)
foreach ($web in $site.AllWebs)
{
foreach ($list in $web.Lists)
{
if ($ListNames -match $list.Title)
{
# Check if view already exists
if ($list.views -match $strViewName)
{
write-host $web -foregroundcolor "blue"
write-host $list.Title -foregroundcolor "blue"
write-host "Preparing to create a view: " $strViewName -foregroundcolor "blue"
write-host "List already exists" -foregroundcolor "blue"
# Check & amend default view function
defaultViewCheck $web $list
}
else
{
write-host $web -foregroundcolor "green"
write-host $list.Title -foregroundcolor "green"
write-host "Preparing to create a view: " $strViewName -foregroundcolor "green"
$newList = $web.Lists.item($list.ID);
$fields = New-Object System.Collections.Specialized.StringCollection
$fields.Add("Title")
[void]$newList.Views.Add($strViewName, $fields, "", 100, $True, $True)
$newList.Update();
write-host "View ", $strViewName , " was created successfully." -foregroundcolor "Green"
# Check & amend default view function
defaultViewCheck $web $list
}
}
}
}
write-host "Complete"
$site.Dispose(); ##ENFORCED DISPOSAL!!!