I'm using the dotnet framework's(4.5) RunSpace and Pipeline classes to invoke powershell from my C# application.
runspace = RunspaceFactory.CreateRunspace();
runspace.ThreadOptions = PSThreadOptions.UseCurrentThread;
runspace.Open();
Log("Create runspace pipeline");
pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(_scriptText);
Log("Invoke scripting");
try
{
results = pipeline.Invoke();
}
catch (Exception e)
{
//Exception handling code
}
Log("Script complete");
// results processing code
I have the thread that is executing this snippet of code impersonated as a particular user. The user details will be provided during runtime and I impersonate as that user and run this code. The impersonation works correctly - I have confirmed this using the Name() method for the Thread owner's identity and also by creating a file in the above code snippet and checking its owner. But, if I do a 'whoami' on the PowerShell script which is getting executed in the RunSpace/Pipeline, the user that is printed is NOT the owner of the thread that invoked the above code but instead the System admin account which owns the application process.
Whatever I do, I cannot get the Powershell to run as the impersonated user. It feels like Runspace just ignores the user impersonation I have done in C#. How do I invoke the Runspace for running powershell as the user I want to impersonate as?
Sorry posting this as an answer straight away as I cant comment as I dont have level 50 rep yet. Anyway, pretty sure you can just copy the c# from this module KelvinTegelaar has already made: https://github.com/KelvinTegelaar/RunAsUser
I use it, and it works great. Its a PowerShell module, but its most c# anyway. In PowerShell you use it like:
invoke-ascurrentuser -scriptblock $scriptblock -UseWindowsPowerShell
and the c# does the impersonation and runs the PowerShell Scriptblock you gave it (as the user impersonated), so sounds like its what you need?