如何执行多行powershell命令

时间:2018-08-14 15:58:31

标签: c# asp.net powershell

尝试在asp.net c#中执行PowerShell命令,但未返回任何结果,我在哪里出错?

var shell = PowerShell.Create();
var script = $@"$Groups = Get-ADGroup {groupname}; $members = ForEach ($Group in $Groups) {{Get-AdGroupMember -Identity $Group -Recursive}} ; $members | Get-AdUser -Properties Department | Select-Object Name, Department | Sort Department, Name";
shell.Commands.AddScript(script);
var results = shell.Invoke();

foreach (var psObject in results)
{
    dt.Rows.Add(new object[] { psObject.Members["Name"].Value, psObject.Members["Department"].Value });
}

Gridview2.DataSource = dt;
Gridview2.DataBind();

它在PowerShell中完美执行。按照suggested answer在命令行之间分隔命令无效。

编辑-我再次查看了Powershell,并意识到它不必要地复杂。我将其更改为以下内容,现在可以使用了。仍然无法解释为什么从asp.net运行时返回结果导致Powershell无法正常工作的情况。

Get-AdGroupMember -Identity {groupname} -Recursive | Get-AdUser -Properties Department | Select-Object Name, Department | Sort Department, Name

0 个答案:

没有答案