0

我正在尝试从 vCenter 为主机收集性能数据。我已经创建了这个 powershell 脚本。它可以工作,但需要很长时间才能完成。有没有更好更有效的方法来从 vCenter 中检索数据。

Connect-VIServer "vcenter.server.com" -User user123 -Password testpassword
$allvms = @()
$allhosts = @()
$hosts = Get-VMHost
$vms = Get-Vm

foreach($vmHost in $hosts){
  $hoststat = "" | Select HostName, MemMax, MemAvg, MemMin, CPUMax, CPUAvg, CPUMin
  $hoststat.HostName = $vmHost.name

  $statcpu = Get-Stat -Entity ($vmHost)-start (get-date).AddDays(-1) -Finish (Get-Date)-MaxSamples 10 -stat cpu.usage.average
  $statmem = Get-Stat -Entity ($vmHost)-start (get-date).AddDays(-1) -Finish (Get-Date)-MaxSamples 10 -stat mem.usage.average

  $cpu = $statcpu | Measure-Object -Property value -Average -Maximum -Minimum
  $mem = $statmem | Measure-Object -Property value -Average -Maximum -Minimum

  $hoststat.CPUMax = $cpu.Maximum
  $hoststat.CPUAvg = $cpu.Average
  $hoststat.CPUMin = $cpu.Minimum
  $hoststat.MemMax = $mem.Maximum
  $hoststat.MemAvg = $mem.Average
  $hoststat.MemMin = $mem.Minimum
  $allhosts += $hoststat
}
$allhosts | Select HostName, MemMax, MemAvg, MemMin, CPUMax, CPUAvg, CPUMin | Export-Csv "c:\output\Hosts.csv" -noTypeInformation
4

2 回答 2

1

您可以使用单个 get-stat 调用从多个主机实体收集多个指标,例如,

get-stat -Entity $hosts -MaxSamples 10 -Stat "cpu.usage.average","mem.usage.average"

然后用于Group-Object解析结果。LucD在这里的帖子可能会有所帮助。

我想知道您是否需要$vms = Get-Vm,因为您发布的代码没有引用该代码。

您的 PS 会话应该与 vCenter 数据库在同一个 LAN 上。另请参见kb.vmware.com/kb/2007388

于 2014-08-20T22:13:18.713 回答
1

考虑以下代码,它将处理转移到 PowerShell 后台作业中:

Connect-VIServer "vcenter.server.com" -User user123 -Password testpassword
$allvms = @()
$allhosts = @()
$hosts = Get-VMHost;
$vms = Get-Vm;

# Define the code that will be executed as part of the background job
$Job = {
  $hoststat = @{};

  $statcpu = Get-Stat -Entity $args[0] -start (get-date).AddDays(-1) -Finish (Get-Date)-MaxSamples 10 -stat cpu.usage.average;
  $statmem = Get-Stat -Entity $args[0] -start (get-date).AddDays(-1) -Finish (Get-Date)-MaxSamples 10 -stat mem.usage.average;

  $cpu = $statcpu | Measure-Object -Property value -Average -Maximum -Minimum;
  $mem = $statmem | Measure-Object -Property value -Average -Maximum -Minimum;

  $hoststat.HostName = $args[0];
  $hoststat.CPUMax = $cpu.Maximum;
  $hoststat.CPUAvg = $cpu.Average;
  $hoststat.CPUMin = $cpu.Minimum;
  $hoststat.MemMax = $mem.Maximum;
  $hoststat.MemAvg = $mem.Average;
  $hoststat.MemMin = $mem.Minimum;

  return $hoststat;
}

$JobList = @();
foreach($vmHost in $hosts){
    $JobList += Start-Job -ScriptBlock $Job -Name $vmHost.Name -ArgumentList $vmHost.Name;
}

Wait-Job -Job $JobList;
$JobList | % { $allhosts += Receive-Job -Job $PSItem; };
$allhosts | Select HostName, MemMax, MemAvg, MemMin, CPUMax, CPUAvg, CPUMin | Export-Csv "c:\output\Hosts.csv" -noTypeInformation
于 2014-08-20T21:37:29.373 回答