Impersonation and Hosting PowerShell

PowerShell Team

Some of you reported that Impersonation doesn’t work while hosting PowerShell in applications.  The problem occurs when PowerShell’s pipeline is invoked in the following way from an ASP.NET application:

         WindowsIdentity winId = (WindowsIdentity)HttpContext.Current.User.Identity;


            WindowsImpersonationContext ctx = null;



                ctx = winId.Impersonate();

                Runspace myRunSpace = RunspaceFactory.CreateRunspace();


                Pipeline pipeline = myRunSpace.CreatePipeline(“[System.Security.Principal.WindowsIdentity]::GetCurrent().Name”);

                System.Collections.ObjectModel.Collection<PSObject> objectRetVal = pipeline.Invoke();







Notice the thread’s identity is changed to impersonate CurrentUser identity but the pipeline.Invoke() results show the identity of the current process.  This is because pipeline.Invoke() method creates a thread called “Pipeline Execution Thread” and the command/script is executed in this new thread. In .net 2.0, by default the impersonation token does not flow across threads, so “Pipeline Execution Thread” doesn’t get the impersonation token of the calling thread. You can configure ASP.Net to flow the impersonation token to newly created threads by using “alwaysFlowImpersonationPolicy” and “legacyImpersonationPolicy” configuration elements in aspnet.config file like this:




                             <legacyImpersonationPolicy enabled=”false”/>

                             <alwaysFlowImpersonationPolicy enabled=”true”/>




For more details about impersonation see this article:




Windows PowerShell Development


This posting is provided “AS IS” and confers no rights or warranties.


Discussion is closed.

Feedback usabilla icon