title: SharePoint 2010, Powershell - Loop through all Document Libraries, create view and set it as default
body: <p>I'm having a little trouble with a script I'm working on for SharePoint 2010. I'm only a beginner with Powershell so haven't been able to to spot the no doubt obvious and glaring problem.</p>
  
  <p>The desire for the script is to loop through each web-site in each site collection, create a view for Document Libraries only and set that view as default.</p>
  
  <p><strong>Issue 1)</strong> Currently it appears to enumerate the Document Libraries but then creates the view multiple times in the first library it found. Something is wrong with the foreach loops but I don't know what.</p>
  
  <p><strong>Issue 2)</strong> I need to integrate this section so I can set the view as default but I'm not too sure where to stick it so it loops through with the changes to each library.</p>
  
  <pre><code>$site= New-Object Microsoft.SharePoint.SPSite $siteURL
  $web=$site.OpenWeb()
  $list=$web.Lists["$list"]
  $view=$list.Views["Detailed"]
  $view.DefaultView = $true
  $view.Update()
  $list.Update()
  </code></pre>
  
  <p>Any assistance on these two issues would be of great help:-). Thanks, Ashley</p>
  
  <p><strong>Full Script:</strong></p>
  
  <pre><code>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") {
  
   $site = New-Object Microsoft.SharePoint.SPSite($SiteURL) ;
   $web = $site.OpenWeb($SiteURL);
   $list = $web.Lists.item($listname);
  
   $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]$list.Views.Add("Detailed", $viewfields, "", 100, $true, $true)
  
   $list.Update();
   }}
   $web.Dispose();
   $site.Dispose();
   }
  </code></pre>