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("http://yourserver.com")
$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.