Hyper-V Get-VM in powershell via asp.net c#

1.5k views Asked by At

I am trying to write a web interface that will show the current VMs on a remote Hyper-V host.

So far, I have this

    protected void getVMS(object sender, GridViewCommandEventArgs e)
    {
        //command to run
        string cmdToRun = "get-vm -computername fsyovs02";

        var shell = PowerShell.Create();

        shell.Commands.AddScript(cmdToRun);

        var results = shell.Invoke();

           if (results.Count > 0)
           {

              var builder = new StringBuilder();

              foreach (PSObject vm in results)
              {

                  builder.Append(vm.BaseObject.ToString() + "\r\n");
              }

            ResultBox.Text = Server.HtmlEncode(builder.ToString());
          }
    }

This is returning something, but not what I want. For each VM, it is returning the line

  Microsoft.HyperV.PowerShell.VirtualMachine

What I want is it to display exactly how it does via powershell.

Can anyone help me please - as I am going out of my mind!

Many Thanks Mark

1

There are 1 answers

3
Przemysław Ładyński On BEST ANSWER

Sorry had to edit my answer as you cannot access those types from C#. You should then use the Members collection on PSObject to access particular properties of the VirtualMachine. Please check this approach in your case:

    foreach (PSObject vm in results)
    {       
           builder.Append(vm.Members["Name"].Value + "\r\n");
    }