I have a Powershell script I want to run by C# as another user.
Here is the code to call the ps script from the current session :
using (PowerShell PowerShellInstance = PowerShell.Create())
{
PowerShellInstance.AddScript(RemoveUser);
PowerShellInstance.AddParameter("GID", GID);
try
{
PowerShellInstance.Invoke();
return true;
}
catch (Exception e)
{
Debug.WriteLine(e.StackTrace);
}
return false;
}
This code works perfectly. But now I want to execute it as another user. I saw a lot of code sample talking about a WSManConnectionInfo so I tried this piece of code found in another question :
var password = new SecureString();
Array.ForEach("myStup1dPa$$w0rd".ToCharArray(), password.AppendChar);
PSCredential credential = new PSCredential("anotherUser", password);
WSManConnectionInfo connectionInfo = new WSManConnectionInfo() { Credential = credential };
using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo))
{
runspace.Open();
using (PowerShell PowerShellInstance = PowerShell.Create())
{
PowerShellInstance.Runspace = runspace;
PowerShellInstance.AddScript(RemoveUser);
PowerShellInstance.AddParameter("GID", GID);
try
{
PowerShellInstance.Invoke();
return true;
}
catch (Exception e)
{
Debug.WriteLine(e.StackTrace);
}
return false;
}
}
But at the moment I add a WSManConnectionInfo, I get a "PSRemotingTransportException" saying that Connecting to remote server localhost failed. It seems normal because There isn't anything waiting for a connection to my localhost and I don't want to add one. The runspace works when I implement it like that :
using (Runspace runspace = RunspaceFactory.CreateRunspace())
{
runspace.Open();
using (PowerShell PowerShellInstance = PowerShell.Create())
{
PowerShellInstance.Runspace = runspace;
PowerShellInstance.AddScript(RemoveUser);
PowerShellInstance.AddParameter("GID", GID);
try
{
PowerShellInstance.Invoke();
return true;
}
catch (Exception e)
{
Debug.WriteLine(e.StackTrace);
}
return false;
}
}
It seems that there isn't any remote connection implemented, even if we are in localhost. So can I just add some credentials for another user to execute this code and avoid the remote connection ?