Reputation: 21
I'm encountering an issue while trying to read VMs from an ESXi hypervisor using the following C# function
public static ReadHypervisorVmListRspn ReadHypervisorVmList(ReadHypervisorVmListRqst rqst)
{
PowerShellClient ps = null;
try
{
ps = new PowerShellClient();
var rspn0 = ps.ExecuteScript("Set-ExecutionPolicy -Scope CurrentUser Unrestricted");
var rspn = new PowerShellClient.ExecuteRspn();
// Login to the hypervisor
var cmd = "Connect-VIServer -Server " + rqst.LoginInfo.HostUrl + " -Protocol https -User " + rqst.LoginInfo.HostUserName +
" -Password " + rqst.LoginInfo.HostPassword;
rspn = ps.ExecuteScript(cmd);
if (rspn.Response != "OK")
{
return new ReadHypervisorVmListRspn { Response = "Unable to connect !!" };
}
// Fetch VM information
cmd = "Get-Vm | Select-Object Name,PowerState,NumCPU,MemoryGB,UsedSpaceGB,ProvisionedSpaceGB,@{N='GuestFullName';E={@($_.guest.OSFullName)}},@{N='PrivateIp';E={@($_ | Get-View).Guest.Ipaddress}},@{N='MacAddress';E={($_ | Get-NetworkAdapter).MacAddress}},@{N='Uuid'; E={($_ |Get-View).config.uuid}},@{N='UpTime';E={($_ |Get-View).Summary.QuickStats.Uptimeseconds}},@{n='HardDiskSizeGB'; e={(Get-HardDisk -VM $_ | Measure-Object -Sum CapacityGB).Sum}}";
var rspn1 = ps.ExecuteScript(cmd, true, 1);
if (rspn1.Response.Contains("An item with the same key has already"))
rspn1 = ps.ExecuteScript(cmd);
if (rspn1.Response != "OK")
{
// Logout from the hypervisor
cmd = "Disconnect-VIServer -Confirm:$false;";
var rspn5 = ps.ExecuteScript(cmd);
return new ReadHypervisorVmListRspn { Response = rspn1.Response };
}
// Logout from the hypervisor
cmd = "Disconnect-VIServer -Confirm:$false;";
var rspn4 = ps.ExecuteScript(cmd);
// Process fetched VM information
var rspn3 = rspn1.Output;
var VmInfo = Json4.GetType<List<VmInfo>>(rspn3);
var rspn2 = new ReadHypervisorVmListRspn()
{
Response = "OK",
VmInfo = VmInfo
};
return rspn2;
}
catch (Exception ex)
{
return new ReadHypervisorVmListRspn { Response = "Error" };
}
finally
{
// Clean up resources
ps = null;
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
The function sometimes works successfully, but most of the time I encounter the 'System.OutOfMemoryException' error. It returns errors like:
18-02-2024 16:14:19 Get-NetworkAdapter Exception of type 'System.OutOfMemoryException' was thrown.
18-02-2024 16:14:20 Get-NetworkAdapter Exception of type 'System.OutOfMemoryException' was thrown.
18-02-2024 16:14:20 Get-HardDisk Exception of type 'System.OutOfMemoryException' was thrown.
18-02-2024 16:14:21 Get-View Exception of type 'System.OutOfMemoryException' was thrown.
I've also tried fetching VMs in batches using a loop, but the issue persists. Is there any possible way to fix this issue?
Upvotes: 1
Views: 35