ASP.NET PowerShell Impersonation


I have developed an ASP.NET MVC Web Application to execute PowerShell scripts.

I am using the VS web server and can execute scripts fine.

However, a requirement is that users are able to execute scripts against AD to perform actions that their own user accounts are not allowed to do.

Therefore I am using impersonation to switch the identity before creating the PowerShell runspace:

I have tested using a domain admin account and I get the following exception when calling runspace.Open():

Security Exception
Description: The application attempted to perform an operation not allowed by the security policy. To grant this application the required permission please contact your system administrator or change the application’s trust level in the configuration file.
Exception Details: System.Security.SecurityException: Requested registry access is not allowed.

The web application is running in full trust and I have explicitly added the account I am using for impersonation to the local administrators group of the machine (even though the domain admins group was already there).

I’m using advapi32.dll LogonUser call to perform the impersonation in a similar way to this post (

Any help appreciated as this is a bit of a show stopper at the moment.



Does this blog post help? Comes straight from the PowerShell devs. Essentially, PowerShell starts a new thread to run the pipeline, and since .NET2.0 doesn’t allow the thread to use the impersonation from the calling thread, it fails.


ASP.NET PowerShell Impersonation by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply