Skip to main content
  • Place orders quickly and easily
  • View orders and track your shipping status
  • Enjoy members-only rewards and discounts
  • Create and access a list of your products
  • Manage your Dell EMC sites, products, and product-level contacts using Company Administration.

Article Number: 000148756


Executing Microsoft PowerShell Scripts that use the VMware PowerCLI Snap-In via C# and Microsoft .NET

Summary: Dell Systems Management Solutions: Dell OpenManage, iDRAC, Repository Manager, Microsoft SCCM, Chassis Managment Controller, and more

Article Content


Symptoms

PowerShell is a flexible scripting language that can be used to automate and accomplish a great deal of administrative tasks in Windows.  PowerShell’s flexibility and extensibility is further enhanced by integrating with VMware’s PowerCLI Snap-in, thereby extending the same automation benefits to the VMware vSphere environment. Calling PowerShell scripts programmatically makes creating an interface to execute commands and output data quick and easy. This post walks through the process to capture data from PowerShell and output it in XML (Extensible Markup Language).

PowerShell is Microsoft’s common scripting language that comes pre-installed on Windows Server 2008 R2. PowerCLI is a PowerShell Snap in from VMware that adds cmdlets to PowerShell to manage vSphere deployments. PowerCLI can be downloaded from VMware’s website at

http://downloads.vmware.com/downloads/download.do?downloadGroup=PCLI501.

The environment that’s used in this article consists of Visual Studio 2010 Professional along with Windows Server 2008 R2, .NET 4, PowerShell v2.0, and PowerCLI 5.0. The article assumes that the reader has some experience with C#, C# DataSets and XML.

First, the function queries vCenter for a list of Hypervisors, and then populates a data structure with that information. While PowerShell is flexible with output types, the data structure is output as an XML file, since XML is flexible, easy to use, and .NET interacts with it natively. In other scenarios, an SQL database or INI file could be used.

Before PowerShell can interact with .NET, the assemblies need to be called and referenced in the .NET code. As shown in Figure 1 and 2, the following steps instruct how to add these assemblies. Right click on "References" -> "Add Reference". Navigate to either:

C:\Program Files (x86)\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0

C:\Program Files\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0

SLN311384_en_US__1I_Reference_dv_v1

Figure 1:
Add Reference

SLN311384_en_US__2I_RecentAssemblyadditions_dv_v1

Figure 2: Recent Assembly additions

Now that the steps shown in Figure 1 and 2 are completed, the reference assembly has to be included at the top of the file by implementing the following assemblies:

using System.Management.Automation;
using System.Management.Automation.Runspaces;

Once the assemblies have been added, the developer can instantiate a PowerShell runtime instance and begin to add scripts to it. In the following function, vCenter is queried for information regarding the Hypervisor hosts. The information is parsed and then stored in the file hypervisors.xml.

 

 

        void Execute_vCenter_Tasks(string vCenterIp, string vCenterUsername, string vCenterPassword)

        {             

                var shell = PowerShell.Create();

//The variable above instantiates a PowerShell object that you can add   

//scripts to

                //Add the VMware plugin to issue PowerCli commands

                //Each command should end with a semi-colon as this instructs PowerShell

                //to issue a new line.

                //Lastly, the System.Environment.NewLine equates to the carriage return

                string PsCmd = "add-pssnapin VMware.VimAutomation.Core; $vCenterServer = '" + vCenterIp + "';$vCenterAdmin = '" + vCenterUsername + "' ;$vCenterPassword = '" + vCenterPassword + "';" + System.Environment.NewLine;

                //The next line issues the connection string.

                PsCmd = PsCmd + "$VIServer = Connect-VIServer -Server $vCenterServer -User $vCenterAdmin -Password $vCenterPassword;" + System.Environment.NewLine;

                //Query and obtain a list of hypervisors

                PsCmd = PsCmd + "$VMHosts = (Get-VMHost | select Name );" + System.Environment.NewLine;

                //Establish an index for the array. Use the number of Hypervisors

                PsCmd = PsCmd + "$hostIndex = $VMHosts.Count;" + System.Environment.NewLine;

                //Write the output to a variable

                PsCmd = PsCmd + "for ($i=0; $i -le $hostIndex - 1; $i++){ Write-Output $VMHosts[$i].Name}";

           

                //Add the script and execute it.

                shell.Commands.AddScript(PsCmd);

                var results = shell.Invoke();

 

                //Parse the results and store the output into XML.

                if (results.Count > 0)

                {

                    var builder = new StringBuilder();

 

                    DataSet ds = new DataSet();

                    DataTable dt = new DataTable();

 

                    dt.Columns.Add("name");

                    dt.Columns.Add("hyperIP");

                    dt.Columns.Add("hyperUser");

                    dt.Columns.Add("hyperPassword");

                    dt.Columns.Add("idracUser");

                    dt.Columns.Add("idracPassword");

                    dt.Columns.Add("idracIp");

                    ds.Tables.Add(dt);

 

                    foreach (var psObject in results)

                    {

                        //Query the hypervisor name’s and grab the IP addresss

                        IPAddress[] ipList = System.Net.Dns.GetHostAddresses(psObject.ToString());

 

                        foreach (IPAddress ip in ipList)

                        {

                        //Add the data into a datarow and insert it into the structure

                            DataRow dr = ds.Tables[0].NewRow();

                            dr[0] = psObject;

                            dr[1] = ip;

                            dr[2] = "";

                            dr[3] = "";

                            dr[4] = "";

                            dr[5] = "";

                            dr[6 ] = "";

                            ds.Tables[0].Rows.Add(dr);

                        }

                    }

 

                    ds.AcceptChanges();

                    ds.WriteXml(Server.MapPath("hypervisors.xml"));

                    //Write the XML file and close it out

                    //The bottom function then populates the data into the datagrid

binddata();

                }       

        }

 

Figure 3: C# Source code with PowerShell/PowerCLI

The XML end results are displayed below:

 

<?xml version="1.0" standalone="yes"?>

<vCheckSettings>

  <Host>

    <name>esx1.v50a.vse.lab</name>

    <hyperIP>172.162.27.101</hyperIP>

    <hyperUser>root</hyperUser>

    <hyperPassword>password+123</hyperPassword>

    <idracUser>root</idracUser>

    <idracPassword>calvin</idracPassword>

    <idracIp>172.10.27.101</idracIp>

  </Host>

 

 <Host>

    <name>esx2.v50a.vse.lab</name>

    <hyperIP>172.162.27.102</hyperIP>

    <hyperUser>root</hyperUser>

    <hyperPassword>password+123</hyperPassword>

    <idracUser>root</idracUser>

    <idracPassword>calvin</idracPassword>

    <idracIp>172.10.27.102</idracIp>

  </Host>

</vCheckSettings>

 

Figure 4: Hypervisors.XML

Once the XML file contains the queried data, it is easy to output that data to a webpage. A sample webpage that displays the XML data is shown below. There are many different, easy ways to display XML data, but a webpage was selected so that end users are not required to have PowerShell and PowerCLI environments configured.  Rather the end user clicks on Query vCenter which in turn calls the sample code.

SLN311384_en_US__3I_Management_Server_dv_v1

Figure 5: Sample datagrid that displays the XML data. 

In this post, I examined some administrative task automation possibilities involving .NET, PowerShell and PowerCLI. There are many more possibilities for automation utilizing these tools. With the example provided here, one can see that its relatively straightforward to execute PowerShell scripting programmatically. Utilizing any GUI, such as a web interface, enables non-technical users the ability to run PowerShell scripts on demand.

Article Properties


Last Published Date

21 Feb 2021

Version

3

Article Type

Solution