Sharing the experience search

Search sharing-the-experience.blogspot.com

Wednesday, April 13, 2011

Powershell and Sharepoint: Impersonation

Recently I wanted to simulate the creation of the list item programmatically with impersonation.  This is an ideal example for using  PowerShell.
If you are new to PowerShell - you are welcome to read PowerShell First Aid\CPR
  I wanted to use explicit impersonation  and have found a wonderful article with a simple example

Explicit impersonation means creating an SPUser object for the administrator, getting the SPToken of the user and then using this token to open the SPSite.
I was trying to use  web.AllUsers["{your_domain}\\{your_username}"] but sometime it returns null; I have realized it's more stable to use:
web.AllUsers.GetByID

To find the id - just click on the user that you want to use in sharepoint site - look at the id parameter in the url: {url of the site}/_layouts/userdisp.aspx?ID=


And finally, here is the code to add a new list item with impersonation through PowerShell:

$user=$web.AllUsers.GetByID(1073741823)

$token = $user.UserToken;

$impWebObj= New-Object Microsoft.SharePoint.SPSite($web.Url, $token);

$imperWeb = $impWebObj.OpenWeb();

$arcase=$imperWeb.Lists["At-Risk Case"]

$item = $arcase.Items.Add()

$item["Employee"]="000220"

$item.Update()


Make it easy, make it through PowerShell

No comments:

Post a Comment