<p>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?</p>

<p>Basically, the script that I have so far looks something like this:</p>

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

Runspace runspace = RunspaceFactory.CreateRunspace(rc);
runspace.Open();

Pipeline pipeline = runspace.CreatePipeline();
using (pipeline)
{
   pipeline.Commands.AddScript("Get-Mailbox -identity 'user.name'");
   pipeline.Commands.Add("Out-String");

   Collection&lt;PSObject&gt; results = pipeline.Invoke();

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

   runspace.Close();

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

return resultString;
</code></pre>

[{'answer_id': 11811, 'author': 'Kev', 'author_id': 419, 'author_profile': 'https://Stackoverflow.com/users/419', 'pm_score': 2, 'selected': False, 'text': '<p>In your ASP.NET app, you will need to impersonate a valid AD account with the correct permissions:</p>\n\n<p><a href="http://support.microsoft.com/kb/306158" rel="nofollow noreferrer">http://support.microsoft.com/kb/306158</a></p>\n'}, {'answer_id': 12554, 'author': 'Otto', 'author_id': 519, 'author_profile': 'https://Stackoverflow.com/users/519', 'pm_score': 3, 'selected': False, 'text': '<p>Here is a class that I use to impersonate a user.</p>\n\n<pre><code>using System;\nusing System.Data;\nusing System.Configuration;\nusing System.Web;\nusing System.Web.Security;\nusing System.Web.UI;\nusing System.Web.UI.WebControls;\nusing System.Web.UI.WebControls.WebParts;\nusing System.Web.UI.HtmlControls;\n\nnamespace orr.Tools\n{\n\n    #region Using directives.\n    using System.Security.Principal;\n    using System.Runtime.InteropServices;\n    using System.ComponentModel;\n    #endregion\n\n    /// &lt;summary&gt;\n    /// Impersonation of a user. Allows to execute code under another\n    /// user context.\n    /// Please note that the account that instantiates the Impersonator class\n    /// needs to have the \'Act as part of operating system\' privilege set.\n    /// &lt;/summary&gt;\n    /// &lt;remarks&gt;   \n    /// This class is based on the information in the Microsoft knowledge base\n    /// article http://support.microsoft.com/default.aspx?scid=kb;en-us;Q306158\n    /// \n    /// Encapsulate an instance into a using-directive like e.g.:\n    /// \n    ///     ...\n    ///     using ( new Impersonator( "myUsername", "myDomainname", "myPassword" ) )\n    ///     {\n    ///         ...\n    ///         [code that executes under the new context]\n    ///         ...\n    ///     }\n    ///     ...\n    /// \n    /// Please contact the author Uwe Keim (mailto:uwe.keim@zeta-software.de)\n    /// for questions regarding this class.\n    /// &lt;/remarks&gt;\n    public class Impersonator :\n        IDisposable\n    {\n        #region Public methods.\n        /// &lt;summary&gt;\n        /// Constructor. Starts the impersonation with the given credentials.\n        /// Please note that the account that instantiates the Impersonator class\n        /// needs to have the \'Act as part of operating system\' privilege set.\n        /// &lt;/summary&gt;\n        /// &lt;param name="userName"&gt;The name of the user to act as.&lt;/param&gt;\n        /// &lt;param name="domainName"&gt;The domain name of the user to act as.&lt;/param&gt;\n        /// &lt;param name="password"&gt;The password of the user to act as.&lt;/param&gt;\n        public Impersonator(\n            string userName,\n            string domainName,\n            string password)\n        {\n            ImpersonateValidUser(userName, domainName, password);\n        }\n\n        // ------------------------------------------------------------------\n        #endregion\n\n        #region IDisposable member.\n\n        public void Dispose()\n        {\n            UndoImpersonation();\n        }\n\n        // ------------------------------------------------------------------\n        #endregion\n\n        #region P/Invoke.\n\n        [DllImport("advapi32.dll", SetLastError = true)]\n        private static extern int LogonUser(\n            string lpszUserName,\n            string lpszDomain,\n            string lpszPassword,\n            int dwLogonType,\n            int dwLogonProvider,\n            ref IntPtr phToken);\n\n        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]\n        private static extern int DuplicateToken(\n            IntPtr hToken,\n            int impersonationLevel,\n            ref IntPtr hNewToken);\n\n        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]\n        private static extern bool RevertToSelf();\n\n        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]\n        private static extern bool CloseHandle(\n            IntPtr handle);\n\n        private const int LOGON32_LOGON_INTERACTIVE = 2;\n        private const int LOGON32_PROVIDER_DEFAULT = 0;\n\n        // ------------------------------------------------------------------\n        #endregion\n\n        #region Private member.\n        // ------------------------------------------------------------------\n\n        /// &lt;summary&gt;\n        /// Does the actual impersonation.\n        /// &lt;/summary&gt;\n        /// &lt;param name="userName"&gt;The name of the user to act as.&lt;/param&gt;\n        /// &lt;param name="domainName"&gt;The domain name of the user to act as.&lt;/param&gt;\n        /// &lt;param name="password"&gt;The password of the user to act as.&lt;/param&gt;\n        private void ImpersonateValidUser(\n            string userName,\n            string domain,\n            string password)\n        {\n            WindowsIdentity tempWindowsIdentity = null;\n            IntPtr token = IntPtr.Zero;\n            IntPtr tokenDuplicate = IntPtr.Zero;\n\n            try\n            {\n                if (RevertToSelf())\n                {\n                    if (LogonUser(\n                        userName,\n                        domain,\n                        password,\n                        LOGON32_LOGON_INTERACTIVE,\n                        LOGON32_PROVIDER_DEFAULT,\n                        ref token) != 0)\n                    {\n                        if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)\n                        {\n                            tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);\n                            impersonationContext = tempWindowsIdentity.Impersonate();\n                        }\n                        else\n                        {\n                            throw new Win32Exception(Marshal.GetLastWin32Error());\n                        }\n                    }\n                    else\n                    {\n                        throw new Win32Exception(Marshal.GetLastWin32Error());\n                    }\n                }\n                else\n                {\n                    throw new Win32Exception(Marshal.GetLastWin32Error());\n                }\n            }\n            finally\n            {\n                if (token != IntPtr.Zero)\n                {\n                    CloseHandle(token);\n                }\n                if (tokenDuplicate != IntPtr.Zero)\n                {\n                    CloseHandle(tokenDuplicate);\n                }\n            }\n        }\n\n        /// &lt;summary&gt;\n        /// Reverts the impersonation.\n        /// &lt;/summary&gt;\n        private void UndoImpersonation()\n        {\n            if (impersonationContext != null)\n            {\n                impersonationContext.Undo();\n            }\n        }\n\n        private WindowsImpersonationContext impersonationContext = null;\n\n        // ------------------------------------------------------------------\n        #endregion\n    }\n}\n</code></pre>\n'}, {'answer_id': 448051, 'author': 'Eldila', 'author_id': 889, 'author_profile': 'https://Stackoverflow.com/users/889', 'pm_score': 2, 'selected': True, 'text': "<p>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.</p>\n"}, {'answer_id': 1499913, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>You might need a patch.</p>\n\n<p>From: <a href="http://support.microsoft.com/kb/943937" rel="nofollow noreferrer">http://support.microsoft.com/kb/943937</a></p>\n\n<blockquote>\n  <p><strong>An application cannot impersonate a\n  user and then run Windows PowerShell\n  commands in an Exchange Server 2007\n  environment</strong></p>\n  \n  <p>To resolve this problem, install\n  Update Rollup 1 for Exchange Server\n  2007 Service Pack 1.</p>\n</blockquote>\n'}]
['https://Stackoverflow.com/questions/11806', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/889/']