gpt4 book ai didi

c# - 执行 C# 交互式 powershell 脚本

转载 作者:太空宇宙 更新时间:2023-11-03 19:45:02 24 4
gpt4 key购买 nike

假设我使用 C# 执行一个 powershell 脚本。脚本执行的结果是需要凭据才能继续。

例子:

Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(scriptText);
... = pipeline.Invoke();
// i must enter credentials in order to continue the script execution

是否可以通过编程方式实现这种交互?

最佳答案

IMO 最简单的方法是使用有效凭据连接到目标计算机,然后您可以在没有任何凭据提示的情况下执行任何代码,为此,您需要创建一个 PSCredential 对象,它是一个用户名和一个 SecureString 密码。

要将纯文本转换为 SecureString,您可以使用此方法:

private SecureString GetSecurePassword(string password)
{
var securePassword = new SecureString();
foreach (var c in password)
{
securePassword.AppendChar(c);
}

return securePassword;
}

然后下一步是为目标计算机创建一个 WSManConnectionInfo 对象,并添加凭据,您可以再次使用此方法:

WSManConnectionInfo GetConnectionInfo(string computerName)
{
PSCredential creds = new PSCredential("UserName",
GetSecurePassword("Password"));

Uri remoteComputerUri = new Uri(string.Format("http://{0}:5985/wsman", computerName));
WSManConnectionInfo connection = new WSManConnectionInfo(remoteComputerUri,
"http://schemas.microsoft.com/powershell/Microsoft.PowerShell",
creds);

return connection;
}

最后,连接到目标计算机并创建一个运行空间:

WSManConnectionInfo connectionInfo = GetConnectionInfo("computerName");
Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo);

回到你的代码:

Pipeline pipeline = runspace.CreatePipeline();
[...]

关于c# - 执行 C# 交互式 powershell 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46787381/

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