Second Life of a Hungarian SharePoint Geek

July 15, 2013

Injecting HttpContext and SPContext into your PowerShell scripts

Filed under: PowerShell, SP 2010 — Tags: , — Peter Holpar @ 22:10

Two years ago I already write a similar post that shows how to inject HttpContext and SPContext into event receivers or into other type of code running without such context by default.

This time I had to achieve the same from PowerShell to be able to call built-in SharePoint object model methods that were designed to run within an SPContext.

WARNING: The method below is probably not a supported solution. It is only presented here as a technological curiosity, use it at your own risk.

Having the original code it was pretty straightforward to translate the C# version to PowerShell. Here is the result:

# getting site and web references
$site = Get-SPSite("")
$web = $site.OpenWeb("/yourweb")
# injecting contexts
$request = New-Object System.Web.HttpRequest("", $web.Url, "")
$response = New-Object System.Web.HttpResponse(New-Object System.IO.StreamWriter(New-Object System.IO.MemoryStream))
$dummyContext = New-Object System.Web.HttpContext($request, $response)
$dummyContext.Items["HttpHandlerSPWeb"] = [Microsoft.SharePoint.SPWeb]$web
[System.Web.HttpContext]::Current = $dummyContext
# testing result

In a forthcoming post I plan to illustrate how to utilize a SharePoint OM using the freshly injected context information.

WARNING: Do not mix the code above with “standard” PowerShell – SharePoint code. I found that it can interfere with the standard functionality. The method above is intended only to inject context before calling SharePoint OM methods.

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a free website or blog at

%d bloggers like this: