DJDave
DJDave

Reputation: 915

cannot get basic sharepoint powershell script to run

I have a simple powershell script intended to manipulate Sharepoint 2010. I have stripped it down to the minimum to illustrate the problem.

Add-PSSnapin Microsoft.SharePoint.PowerShell -erroraction SilentlyContinue
$siteURL = "http://intranet/"
$site = Get-SPSite($siteURL)

foreach ($web in $site.AllWebs) {
    Write-Host "Inspecting " $web.Title
}

It fails when I introduce the "foreach" loop (so the Snap-in loads OK and Get-SPSite($siteURL) doesn't seem to cause an error).

The error message is

C:\temp\sp_dm.PS1 : Exception has been thrown by the target of an invocation.
At line:1 char:12
+ .\sp_dm.PS1 <<<<
    + CategoryInfo          : NotSpecified: (:) [sp_dm.PS1], TargetInvocationExceptio
    + FullyQualifiedErrorId : System.Reflection.TargetInvocationException,sp_dm.PS1

The problem isn't line:1 of the script, the message refers to line:1 of the command that I type to run it (I changed the name of the script and the char:12 changed accordingly). BUt as I say, the error is generated by the foreach loop, and the code occurs in many examples on the Net, so there is something starnge about my local SharePoint. Any suggestions?

Upvotes: 2

Views: 7148

Answers (4)

Basyonic
Basyonic

Reputation: 579

Solved for me by using elevated privileges block. Also, don't forget to dispose sharepoint SPSite and SPWeb objects.

[Microsoft.SharePoint.SPSecurity]::RunWithElevatedPrivileges({
$Site = Get-SPSite $siteUrl
Foreach ($web in $Site.AllWebs)
{
    #do something..
    $web.Dispose()
}   
$Site.Dispose()
}); 

Upvotes: 0

Sean
Sean

Reputation: 300

This is a late answer, but I came here from a google search and I'd like to resolve this for any future visitors.

The exact same issue/cause is described here: https://sharepoint.stackexchange.com/questions/17247/spsite-allwebs-returns-error

Basically, it is a permissions issue. If you added the account you are running the script as to the permissions of the site collection in question, this error should go away.

Upvotes: 4

SlightlyBent
SlightlyBent

Reputation: 119

Perhaps FullyQualifiedErrorId in error message gives a hint about root cause of problem?

That would seem to indicate that $siteURL needs to include FQDN. Maybe instead of $siteURL = "http://intranet/" you'd need $siteURL = "http://intranet.yourdomain.com".

Upvotes: -1

CB.
CB.

Reputation: 60976

try this change:

$siteURL = "http://intranet/"
$site = Get-SPWeb($siteURL)

    foreach ($web in $site.Site.AllWebs)

Upvotes: 1

Related Questions