"Requested registry access is not allowed" When Attempting to Run PowerShell Script on Remote Machine Using Impersonation
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.