使用不同的凭据从C#调用Powershell命令

时间:2013-06-12 13:49:25

标签: c# powershell credentials

我需要从C#执行一些powershell命令,我正在使用此代码

Runspace rs = RunspaceFactory.CreateRunspace();
rs.Open();
PowerShell ps = PowerShell.Create();
ps.Runspace = rs;
ps.AddCommand("Add-PSSnapin").AddArgument("Citrix*");
ps.Invoke();
// other commands ...

这可以正常工作但现在没有足够权限使用powershell的用户应该执行此应用程序。有没有办法用不同的凭据执行powershell代码? 我的意思是这样的

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...

1 个答案:

答案 0 :(得分:3)

未经测试的代码......但这应该适合您。我使用类似的东西运行远程PowerShell(只需设置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;
}