I have the following code that I have tested and works:
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<PSObject> results = pipeline.Invoke();
}
However, when I try to include the function in a different project so that it is called from a webservice it throws an execption:
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.
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:
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,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With