Reputation: 9644
I need to execute a couple of powershell command from C#, and I'm using this code
Runspace rs = RunspaceFactory.CreateRunspace();
rs.Open();
PowerShell ps = PowerShell.Create();
ps.Runspace = rs;
ps.AddCommand("Add-PSSnapin").AddArgument("Citrix*");
ps.Invoke();
// other commands ...
This works correctly but now a user without sufficient rights to use powershell should execute this application. Is there a way to execute powershell code with different credentials? I mean something like this
var password = new SecureString();
Array.ForEach("myStup1dPa$$w0rd".ToCharArray(), password.AppendChar);
PSCredential credential = new PSCredential("serviceUser", password);
// here I miss the way to link this credential object to ps Powershell object...
Upvotes: 10
Views: 9464
Reputation: 116
Untested code...but this should work for you. I use something similar to run remote powershell (Just set WSManConnectionInfo.ComputerName).
public static Collection<PSObject> GetPSResults(string powerShell, PSCredential credential, bool throwErrors = true)
{
Collection<PSObject> toReturn = new Collection<PSObject>();
WSManConnectionInfo connectionInfo = new WSManConnectionInfo() { Credential = credential };
using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo))
{
runspace.Open();
using (PowerShell ps = PowerShell.Create())
{
ps.Runspace = runspace;
ps.AddScript(powerShell);
toReturn = ps.Invoke();
if (throwErrors)
{
if (ps.HadErrors)
{
throw ps.Streams.Error.ElementAt(0).Exception;
}
}
}
runspace.Close();
}
return toReturn;
}
Upvotes: 5