如何将从 powershell 脚本返回的多个值填充到 HTML 下拉列表中?

How to fill multiple values returned from powershell script into HTML dropdownlist?

我正在通过我的 powershell 脚本获取林中的域列表,我想在下拉列表中填充这些值。基于所选的域,我想在另一个下拉列表中加载 AD 组。我准备好了脚本,但不知道如何填写下拉列表。

我正在使用 System.Automation.Management 库来管理 powershell 脚本。这是我的函数和脚本。

private string PowerShellExecutor(string script) {
    string outString = "";
    var shell = PowerShell.Create();
    shell.Commands.AddScript(script);
    var results = shell.Invoke();
    if (results.Count>0)
    {
        var builder = new StringBuilder();
        foreach (var psObj in results)
        {
            builder.Append(psObj.BaseObject.ToString() + "\r\n");

        }
        outString = Server.HtmlEncode(builder.ToString());
    }
    return outString;
}

<div class="col-md-12">
            @Html.DropDownList("ddlDirectory", new SelectList(PowerShellExecutor(AppDomain.CurrentDomain.BaseDirectory + "Shell\Get\ADDomain.ps1")), "Select Domain", new { @class = "form-control"})
</div>

我的脚本有这个代码:Get-ADForest | Select -ExpandProperty 域 哪个 returns 域列表。

下拉框需要填写的值: 域名1 域名2 ..

正在运行的更新函数:

public List<SelectListItem> PowerShellExecutorLst(string scriptPath)
    {
        string outString = "";
        var shell = PowerShell.Create();
        shell.Commands.AddCommand(scriptPath);
        var results = shell.Invoke();
        if (results.Count > 0)
        {
            var builder = new StringBuilder();
            foreach (var psObj in results)
            {
                builder.Append(psObj.BaseObject.ToString() + "\r\n");

            }
            outString = Server.HtmlEncode(builder.ToString());
        }
        List<string> result = outString.Split(new char[] { '\n' }).ToList();
        List<SelectListItem> listItems = result.Select(s => new SelectListItem { Value = s, Text=s }).ToList();
        shell.Dispose();
        return listItems;
    }