I have some powershell script which is looping into all websites in a webapplication. I have full control permissions in the policy in Central Admin. In this powershell loop I got this error at some sites:

PowerShell and Sharepoint: Exception has been thrown by the target of an invocation.

I think this error occurred because I don't have permissions at some websites. But I would like to skip sites which throw these errors. How can I do that? This is my script:

if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null) { 
    Add-PSSnapin "Microsoft.SharePoint.PowerShell" 

$webApp = [Microsoft.SharePoint.Administration.SPWebApplication]::Lookup("http://portal.myCompany.net") 

foreach ($site in $webApp.Sites) 
     foreach($webSite in $site.AllWebs)
       # some logic

Try to open the PowerShell with Run with Administrator previlages.

The following code worked fine for me,


Add-PSSnapin microsoft.sharepoint.powershell -ErrorAction SilentlyContinue

function GenerateAllSitecollectionsInWebapplication ($url)
    write-host "Sitecollection List Extraction started...." -foregroundcolor red
         $Site=Get-SPSite $url         
         $spWebApp = $Site.WebApplication
         $TotalList = @()
          write-host "Below is the list of all sitecollections for webapplication" + $spWebApp + "..." -foregroundcolor red 
         foreach($allsites in $spWebApp.Sites)
           $list =  $allsites.url 
           write-host $list -foregroundcolor blue        
          write-host "Unable to Extract Sitecollection List..." -foregroundcolor red

GenerateAllSitecollectionsInWebapplication  -Url "www.yoururl.com/"*
  • this script is working, but this is not what I am asking. I would loop into each site collection into all websites. There are some websites where I dont have permissions and got an error. these websites I would like to skip and go to the next website. – Ola Oct 13 '14 at 11:11

Use following to only get sub sites where user has permissions:

$webCollection = web.GetSubwebsForCurrentUser()
  • where do I need to use "web.GetSubwebsForCurrentUser()"? Do I need to replace it for $site.AllWebs? – Ola Oct 9 '14 at 12:10
  • $web = $site.OpenWeb() foreach ($subweb in $Web.GetSubwebsForCurrentUser()) – Aanchal Oct 9 '14 at 12:19
  • you are expecting that I have permissions on all sitecollections. But thats not true. there are some site collections where I dont have permissions and then I got this exception, and the script looping is stopping. – Ola Oct 13 '14 at 10:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.