Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoke Powershell command from C# with different credential

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...
like image 403
Naigel Avatar asked Jun 12 '13 13:06

Naigel


People also ask

Can I run PowerShell command from CMD?

To start a Windows PowerShell session in a Command Prompt window, type PowerShell . A PS prefix is added to the command prompt to indicate that you are in a Windows PowerShell session.

How do I run a PowerShell command remotely?

To run a script on one or many remote computers, use the FilePath parameter of the Invoke-Command cmdlet. The script must be on or accessible to your local computer. The results are returned to your local computer.

How do you execute a PowerShell command?

To run a script, open a PowerShell window, type the script's name (with or without the . ps1 extension) followed by the script's parameters (if any), and press Enter. In keeping with PowerShell's secure by default philosophy, double-clicking a .


1 Answers

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;
}
like image 166
Alan Avatar answered Sep 27 '22 22:09

Alan