Error executing Powershell commands using C #

I have the following code that I 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 a function in another project so that it is called from a web service, it gives execution:

  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.

+4
source share
2 answers

What happens because Impersonator only represents the thread, and PowerShell Runspace runs on a different thread.

To make this work, you need to add:

 runspace.ApartmentState = System.Threading.ApartmentState.STA; runspace.ThreadOptions = System.Management.Automation.Runspaces.PSThreadOptions.UseCurrentThread; 

before opening the workspace.

This will make the run work in the same stream as the issued token.

Hope this helps,

+7
source

Use these namespaces:

 using System.Management.Automation; using System.Management.Automation.Runspaces; using System.Threading; 

Create Runspace with InitialSessionState

 InitialSessionState initialSessionState = InitialSessionState.CreateDefault(); initialSessionState.ApartmentState = ApartmentState.STA; initialSessionState.ThreadOptions = PSThreadOptions.UseCurrentThread; using ( Runspace runspace = RunspaceFactory.CreateRunspace ( initialSessionState ) ) { runspace.Open(); // scripts invocation runspace.Close(); } 
+1
source

All Articles