0

I trying to execute a simple powershell command in c# and output the result. Powershell v5.1 on Server 2016

PowerShell ps = PowerShell.Create();
ps.AddCommand("Get-DhcpServerInDC");
Collection<PSObject> results = ps.Invoke();
StringBuilder sb = new StringBuilder();
foreach (PSObject obj in results) {
    sb.AppendLine(obj.ToString()); }
txt_adt_updateTextbox.Text = sb.ToString();

But instead of getting a list of DHCP servers and their IP addresses, I get the following.

DhcpServerInDC DhcpServerInDC DhcpServerInDC DhcpServerInDC DhcpServerInDC DhcpServerInDC DhcpServerInDC DhcpServerInDC DhcpServerInDC DhcpServerInDC DhcpServerInDC DhcpServerInDC DhcpServerInDC

Gonzo345
  • 1,133
  • 3
  • 20
  • 42
Mark Masic
  • 83
  • 1
  • 11
  • 2
    The nicely formatted list/table you typically see in PowerShell is shown by the host (e.g. console, ISE, etc). In this case _**you**_ are the host, so you need to do the formatting. From the documentaion, it looks like you should get back a collection of WMI objects - if you break at `sb.AppendLine...` you'll be able to see what properties there are on `obj` and then you can grab/format as appropriate. – boxdog Dec 17 '18 at 09:37
  • Thanks for that. What would the code be checking those properties though? And does anyone know where there is a reference for the objects for the various powershell commands? I can't seem to find one. – Mark Masic Dec 17 '18 at 22:09
  • I figured out how to get the specific info I was looking for, for this specific command. (PSObject)obj.Members["DnsName"].Value.ToString() – Mark Masic Dec 17 '18 at 22:58
  • @boxdog if you want to put that comment as an answer I'm happy to mark it as correct. – Mark Masic Dec 17 '18 at 23:00
  • I've added it as an answer. I've also included a link to a previous answer of mine that would have saved you some time and effort if I'd remembered it before :-(. – boxdog Dec 18 '18 at 09:39

1 Answers1

0

The nicely formatted list/table you typically see in PowerShell is shown by the host (e.g. console, ISE, etc). In this case you are the host, so you need to do the formatting.

From the documentaion, it looks like you should get back a collection of WMI objects. Use the technique shown in one of my previous answers to get the data you want:

Dealing with CimObjects with PowerShell inside C#

boxdog
  • 7,894
  • 2
  • 18
  • 27