Virtual Server, WMI and C#

11. August 2006 00:18 by Jaguilar in General  //  Tags:   //   Comments (0)

This code snippet allows you to connect to a remote instance of Virtual Server 2005 R2, via WMI, and retrieve all the Virtual Machine WMI objects.

   1:   
   2:  System.Management.ConnectionOptions co = 
   3:      new System.Management.ConnectionOptions();
   4:  co.Username = user;
   5:  co.Password = password;
   6:   
   7:  ManagementScope scope = new ManagementScope(
   8:      new ManagementPath(@"\\"+computer+
            @"\root\vm\virtualserver"),co);
   9:   
  10:  scope.Connect();
  11:  SelectQuery oq = 
  12:      new SelectQuery("SELECT * FROM VirtualMachine");
  13:   
  14:  ManagementObjectSearcher searcher =
  15:      new ManagementObjectSearcher(scope, oq);
  16:   
  17:  foreach (ManagementObject queryObj in searcher.Get())
  18:  {
  19:       //Do something
  20:  }
 

You need to provide a user and password with enough credentials to query the Virtual Server instance.
BTW, if you ever need to format your code for display on the web, check out this website.

Categories