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
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.