0

Trying to execute a PowerShell command in asp.net c# but it returns no results, where am I going wrong?

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();

It executes perfectly in PowerShell. Separating the command over lines as per suggested answer does not work.

Edit - I took another look at my powershell and realised that it was unecessarily complicated. I changed it to the below and it now works. Still does not explain why something that returns results in powershell does not work when ran from asp.net.

Get-AdGroupMember -Identity {groupname} -Recursive | Get-AdUser -Properties Department | Select-Object Name, Department | Sort Department, Name
6
  • Possible duplicate of Execute multiple line PowerShell Script from C# Commented Aug 14, 2018 at 16:01
  • @Jaxi I had tried that solution but it does not change the outcome. Commented Aug 14, 2018 at 16:09
  • Your script is assigning variables with a result. You need to echo the variable to the end to get those results. put $results at the end of your script or "var results" or whatever prints it in asp.net Commented Aug 14, 2018 at 16:13
  • @RobertCotterman I don't include how I handle the results as I know that part works. After the invoke I have a foreach which creates a datatable. Commented Aug 14, 2018 at 16:20
  • I'm not doubting your knowledge. Sorry if it felt that way. What my point was, is that if you're not asking for an output, you won't get one. Commented Aug 15, 2018 at 2:30

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.