Question:
I have the following code that I have tested and works:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
using (new Impersonator("Administrator", "dev.dev", #########")) { RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create(); Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration); runspace.Open(); RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace); scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted"); Pipeline pipeline = runspace.CreatePipeline(); Command myCmd = new Command(@"C:\test.ps1"); myCmd.Parameters.Add(new CommandParameter("upn", upn)); myCmd.Parameters.Add(new CommandParameter("sipAddress", sipAddress)); pipeline.Commands.Add(myCmd); // Execute PowerShell script Collection } |
However, when I try to include the function in a different project so that it is called from a webservice it throws an execption:
1 2 |
System.Management.Automation.CmdletInvocationException: Access to the registry key 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell' is denied. ---> System.UnauthorizedAccessException: Access to the registry key 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell' is denied. |
I have no idea why this is happening. Any help would be appreciated.
Answer:
What’s happening is that Impersonator only impersonates on the thread, and PowerShell’s Runspace is running on another thread.
To make this work, you need to add:
1 2 3 |
runspace.ApartmentState = System.Threading.ApartmentState.STA; runspace.ThreadOptions = System.Management.Automation.Runspaces.PSThreadOptions.UseCurrentThread; |
just before you open the runspace.
This will force the runspace to run on the same thread as the impersonated token.
Hope this helps,