且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-01-04 16:33:56

未经测试的代码...但这应该对您有用。我使用类似的方法来运行远程Powershell(只需设置WSManConnectionInfo.ComputerName)。

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;
}