I am trying to launch a local instance of PowerShell from C# under different user credentials - and then continue to invoke commands from C#. Is this possible?
If I launch PowerShell directly (not using runspaces) like so:
PowerShell ps = PowerShell.Create()
This doesn't seem to run PS out of process. Thus, it being run under the same credentials as my C# app. If I try to have this code run under impersonation, it actually throws an exception (even though old posts claim you can do so).
If I try to create an out of process Runspace like so:
RunspaceFactory.CreateOutOfProcessRunspace()
there is no way to pass in credentials that I can find.
I know that I can run PS under different credentials and execute script by sending a "Start-Process" command, but then I lose programmatic interactivity with C#. I don't see the results of the script invoke.
It seems that the only way to run PS from C# under a different user by prescribed methods is by using remote runspaces, except specifying the URI as localhost:
PSCredential creds = new PSCredential(UserName, GetSecurePassword(Password));
Uri RemoteComputerUri = Uri ?? new Uri($"{Scheme}://{ComputerName}:{Port}/wsman");
WSManConnectionInfo connectionInfo = new WSManConnectionInfo(RemoteComputerUri, Schema, creds);
using (Runspace remoteRunspace = RunspaceFactory.CreateRunspace(connectionInfo))
{
remoteRunspace.Open();
PowerShell ps = PowerShell.Create();
...
}
But, I don't want to require WSMan / HTTP configuration that remote runspaces requires. I just want to run PS out of process with different credentials but still be able to interact with it via C#.
Thanks in advance!