“Requested registry access is not allowed” When Attempting to Run PowerShell Script on Remote Machine Using Impersonation

后端 未结 1 1398
北海茫月
北海茫月 2020-12-31 13:56

This is the first time I try to execute PowerShell scripts from a C# application. I\'m using PowerShell because I need the output from the .exe I\'m executing on the remote

相关标签:
1条回答
  • 2020-12-31 14:39

    Create the underlying RunSpace for your PowerShell object before impersonating:

    PowerShell ps = PowerShell.Create();
    Runspace runspace = RunspaceFactory.CreateRunspace();
    runspace.Open();
    powerShell.Runspace = runspace;
    
    using (var impersonator = new Impersonator("username", "domain", "password"))
    {
        ps.AddScript(@"Invoke-Command {c:\path\to\file.exe /p} -computername <computerName>");
        results = ps.Invoke();
    }
    runspace.Close()
    

    The RunSpace object encapsulates the OS environment for script execution. the key being accessed is probably HKCU\Environment. That is what I saw when using Perfmon. RunSpace probably uses the HKCU\Environment to populate variables such as $PATH.

    Therefore, when the RunSpace is created, you want it the current user to have access to HKCU\Environment.

    Pulling RunSpace.Open of the impersonated block is mentioned elsewhere as a hack for avoiding the registry access problem. However, merely creating the PowerShell object does not guarantee that the Runspace.Open() is called.

    0 讨论(0)
提交回复
热议问题