Search code examples
c#asp.netpowershellpowercli

Not getting any data when running the following code with c#, powershell and asp.net


What am I doing wrong here? I have the following that actually calls the PowerCLI commands via PowerShell that then returns the data via c# to asp.net. I am not getting any data returned from this even though the command looks correct. Any ideas?

public List<string> ReturnVMsToStrings(string VCENTER_NAME, PSCredential credential)
{
    InitialSessionState PS_ISS;
    VI_SERVER_NAME = VCENTER_NAME;
    string[] IMPORT_MODULES = { "VMWare.PowerCLI", "NimblePowerShellToolkit" };
    PS_ISS = InitialSessionState.CreateDefault();
    PS_ISS.ImportPSModule(IMPORT_MODULES);
    PowerShell PSINSTANCE = PowerShell.Create(PS_ISS);
    Collection<PSObject> result;
    PSINSTANCE.Commands.AddCommand("Connect-VIServer");
    PSINSTANCE.Commands.AddParameter("Server", VI_SERVER_NAME);
    PSINSTANCE.Commands.AddParameter("Credential", credential);
    PSINSTANCE.Invoke();
    // Get the VMs
    PSINSTANCE.Commands.AddCommand("Get-VM");
    result = PSINSTANCE.Invoke();
    List<string> sorted_list = new List<string>();

    if (result.Count > 0)
    {

        foreach (PSObject obj in result)
        {
            sorted_list.Add(obj.Properties["Name"].Value.ToString());
        }

        sorted_list.Sort();
    }
    else
    {
        Exception e = new Exception("Result is empty");
        throw e;
    }

    return sorted_list;
}

Result has no data in it. Running this command from PowerShell returns a bunch of objects from my vCenter. This is really odd with no real reason why this is not working so any pointers would help.


Solution

  • You're calling PSINSTANCE.Invoke() twice, remove the first call and retry.