Thursday, November 26, 2009

How to add users to the Visitor group of a Sharepoint 2010 application using Powershell

There has been a need in my company to add the users to the default visitor group of the sharepoint 2010 application. It is really very time consuming when you have to do it one by one using the Sharepoint UI. I have written a small script for which you can add the users to the default visitor group without any issues.
Here, in the below Script, users.txt contain the list of users that need to be added to the Visitors group...
------------------------------
$Users = Get-Content "C:\Users\service\Documents\PowerShell\users.txt"
foreach ($User in $Users)
{
$url = "http://server1"
$SPUser = New-SPUser -UserAlias $User -Web $url
$Group = "test"
$Owner = "service\account"
$SPSite = Get-SPSite $url
$SPWeb = Get-SPWeb $url
$OpenWeb = $SPSite.OpenWeb()
$OpenWeb.Update()
## can use the below two lines to add a single user to the Visitor Group
#$OpenWeb.SiteGroups.Web.AssociatedVisitorGroup.AddUser
#($Owner,"ps@ms.com",$Group,$Group)
$OpenWeb.SiteGroups.Web.AssociatedVisitorGroup.AddUser($SPUser)
$OpenWeb.Update()
$OpenWeb.Dispose()
}
--------------------------
Hope this helps some one...

Wednesday, November 18, 2009

Exception calling "Update" with "0" argument(s): "The web being updated was changed by an external process."

I came across the error "The web being updated was changed by an external process." when i was debugging a sharepoint code, in which I had changed the System Master Page and Site Master Page present in the page _Layouts/ChangeSiteMasterPage.aspx of the Publishing sharepoint site.

This issue came up because, the SPWeb object was not being disposed. As a result it was becoming stale. And when we try to call the update method of the SPweb object it fails.

The best way to handle this issue is to Dispose the SPWeb Object whenever possible and re-create it once again before you go ahead with any other sharpeoint change through code.

Hope this helps some one....