How do you impersonate an Active Directory user in Powershell?

By : Eldila

I'm trying to run powershell commands through a web interface (ASP.NET/C#) in order to create mailboxes/etc on Exchange 2007. When I run the page using Visual Studio (Cassini), the page loads up correctly. However, when I run it on IIS (v5.1), I get the error "unknown user name or bad password". The biggest problem that I noticed was that Powershell was logged in as ASPNET instead of my Active Directory Account. How do I force my Powershell session to be authenticated with another Active Directory Account?

Basically, the script that I have so far looks something like this:

RunspaceConfiguration rc = RunspaceConfiguration.Create();
PSSnapInException snapEx = null;
rc.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.Admin", out snapEx);

Runspace runspace = RunspaceFactory.CreateRunspace(rc);

Pipeline pipeline = runspace.CreatePipeline();
using (pipeline)
   pipeline.Commands.AddScript("Get-Mailbox -identity ''");

   Collection<PSObject> results = pipeline.Invoke();

   if (pipeline.Error != null && pipeline.Error.Count > 0)
       foreach (object item in pipeline.Error.ReadToEnd())
          resultString += "Error: " + item.ToString() + "\n";


   foreach (PSObject obj in results)
      resultString += obj.ToString();

return resultString;
By : Eldila


This article on MSDN blogs seems to show a way to do it, I've not been able to try it yet, but will let you know when I do.

By : Sam

Exchange 2007 doesn't allow you to impersonate a user for security reasons. This means that it is impossible (at the moment) to create mailboxes by impersonating a user. In order to get around this problem, I created a web service which runs under AD user which has permissions to create email acounts, etc. You can then access this webservice to get access to powershell. Please remember to add the necessary security because this could potentially be a huge security hole.

By : Eldila

This video can help you solving your question :)
By: admin