gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 20:55:04 25 4
gpt4 key购买 nike

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

关于c# - 使用不同的凭据从 C# 调用 Powershell 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17067260/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com