7

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...
Naigel
  • 9,086
  • 16
  • 65
  • 106
  • If not solved, does the following post answer your question? [Run powershell script from c sharp application][1] [1]: http://stackoverflow.com/questions/11120452/run-powershell-script-from-c-sharp-application – Norman Skinner Oct 07 '13 at 18:46

1 Answers1

4

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;
}
Alan
  • 106
  • 7
  • This requires remote execution to be enabled on your machine (`Enable-PSRemoting -force`) and whilst it runs the PowerShell, it doesn't not execute in the context of the credentials specified. It executed it under my logged in user as opposed to the user I provided credentials for. – Axemasta Sep 11 '19 at 14:03