Set-SPHttpContext

Sets the HTTP Context for a given Site and returns a new SPWeb object associated with the new context. When done with a given Site be sure to run Clear-SPHttpContext in order to remove the context.

Set-SPHttpContext -Identity <SPWebPipeBind> [-AssignmentCollection [<SPAssignmentCollection>]]

Parameters

1

ParameterRequiredTypeDescription
IdentityTrueSPWebPipeBind

The web to set the HTTP Context to.

The type must be a valid GUID, in the form 12345678-90ab-cdef-1234-567890bcdefgh; a valid name of Microsoft SharePoint Foundation 2010 Web site (for example, MySPSite1); or an instance of a valid SPWeb object.

AssignmentCollectionFalseSPAssignmentCollection

Manages objects for the purpose of proper disposal. Use of objects, such as SPWeb or SPSite, can use large amounts of memory and use of these objects in Windows PowerShell scripts requires proper memory management. Using the SPAssignment object, you can assign objects to a variable and dispose of the objects after they are needed to free up memory. When SPWeb, SPSite, or SPSiteAdministration objects are used, the objects are automatically disposed of if an assignment collection or the Global parameter is not used.

When the Global parameter is used, all objects are contained in the global store. If objects are not immediately used, or disposed of by using the Stop-SPAssignment command, an out-of-memory scenario can occur.

Detailed Description

Many native SharePoint objects, such as Web Parts, require a valid HTTP Context in order for certain properties to be available. When working within PowerShell there is no HTTP Context so it is necessary to create one. This is accomplished by setting the System.Web.HttpContext.Current static property to a valid object instantiated using the provided SPWeb object. Once created there are SharePoint specific properties that must be set on this object. This cmdlet sets the following (where $context is the HttpContext object):

1. $context.Items["FormDigestValidated"] = true;

2. $context.User = System.Threading.Thread.CurrentPrincipal;

3. $context.Items["Microsoft.SharePoint.SPServiceContext"] = Microsoft.SharePoint.SPServiceContext.GetContext($web.Site);

4. Microsoft.SharePoint.Web.Controls.SPControl.SetContextSite($context, $web.Site);

5. Microsoft.SharePoint.Web.Controls.SPControl.SetContextWeb($context, $web);

When you are finished working with a given Site run Clear-SPHttpContext to set the HttpContext object back to null.

Copyright 2016 Falchion Consulting, LLC

> For more information on this cmdlet and others:

> http://blog.falchionconsulting.com/

> Use of this cmdlet is at your own risk.

> Gary Lapointe assumes no liability.

Examples

------------------EXAMPLE------------------

PS C:\> $web = Set-SPHttpContext "http://demo/"
PS C:\> Write-Host "do something with the web"
PS C:\> Clear-SPHttpContext

This example sets the HttpContext to http://demo.