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:

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:


$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()



Make it easy, make it through PowerShell