Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error executing Powershell commandlets using C#

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.

like image 413
Hugo Avatar asked Jan 20 '23 07:01

Hugo


1 Answers

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,

like image 89
Start-Automating Avatar answered Jan 28 '23 08:01

Start-Automating