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

使用不同的凭据从C#调用Powershell命令,c#,powershell,credentials,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 ... 这可以正常工作,但现在没有

我需要从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...

未经测试的代码…但这应该适用于您。我使用类似于运行远程powershell的东西(只需设置WSManConnectionInfo.ComputerName)

public静态集合GetPSResults(字符串powerShell、PSCredential凭证、bool throwErrors=true)
{
Collection toReturn=新集合();
WSManConnectionInfo connectionInfo=新WSManConnectionInfo(){Credential=Credential};
使用(Runspace Runspace=RunspaceFactory.CreateRunspace(connectionInfo))
{
Open();
使用(PowerShell ps=PowerShell.Create())
{
ps.运行空间=运行空间;
ps.AddScript(powerShell);
toReturn=ps.Invoke();
if(投掷者)
{
如果(ps.HADRERRORS)
{
抛出ps.Streams.Error.ElementAt(0).Exception;
}
}
}
runspace.Close();
}
回归回归;
}

如果没有解决,下面的帖子是否回答了您的问题?[从c sharp应用程序运行powershell脚本][1][1]:这要求在您的计算机上启用远程执行(
Enable PSRemoting-force
),并且当它运行powershell时,它不会在指定凭据的上下文中执行。它在我的登录用户下执行,而不是在我为其提供凭据的用户下执行。
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;
}