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

标签 c# powershell

假设我使用 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/

相关文章:

powershell - 解析大型文本文件最终导致内存和性能问题

powershell - WMI/WQL 查询 powershell 中的双反斜杠

Powershell 在 PSSession 中使用 Start-Process 打开记事本

c# - Linq - 将来自不同对象的子列表合并到一个对象中

c# - C# 和 javascript 中的正则表达式

c# - 找不到 Microsoft.Win32

powershell - 获取内容错误 : "Cannot bind argument to parameter ' Path' because it is null.“

c# - 如何在我的 Compact Framework 应用程序中使用 OpenStreetMap?

c# - 如何通过其子元素提取 DataTemplate 的绑定(bind)?

variables - 为什么使用ByRef时变量要赋值 ".Value"?