Get WMI Memory Values using Perl

2019-02-10 11:13发布

问题:

I need to collect memory data of Windows operating systems using WMI. In that sense, I developed a Perl script to generate such data. However, I wonder if my method is correct and what are the alternatives. It is intended that the method of collecting data is to be as widely as possible in terms of Windows OS's.

If you are not a perlish, this is what I what to check:

MEM_USED = Win32_OperatingSystem->TotalVisibleMemorySize - Win32_OperatingSystem->FreePhysicalMemory
SWAP_USED = (Win32_OperatingSystem->SizeStoredInPagingFiles - Win32_OperatingSystem->FreeSpaceInPagingFiles) /  Win32_OperatingSystem->SizeStoredInPagingFiles

This is my script:

#!/bin/env perl

use Win32::OLE;

use strict;
use warnings;

my $wmi = Win32::OLE->GetObject("winmgmts://./root/cimv2")
  or die "Failed getobject\n";

my $list, my $v;

$list = $wmi->InstancesOf("Win32_OperatingSystem")
  or die "Failed getobject\n";

my $end_time = time;


my ($total_mem, $free_mem, $used_mem, $mem_percent, $free_percent);

foreach $v (in $list) {

  $total_mem = $v->{TotalVisibleMemorySize};
  $free_mem = $v->{FreePhysicalMemory};
  $used_mem = $total_mem - $free_mem;
  $mem_percent = sprintf("%.2f", $used_mem / $total_mem * 100);
  $free_percent  =  sprintf("%.2f", $free_mem / $total_mem * 100);

  print "Memory used: $mem_percent\%\n";
  print "Memory free: $free_percent\%\n";
  print "Memory total: $total_mem kb\n";
  print "Memory used: $used_mem kb\n";
  print "Memory free: $free_mem kb\n";

  my $total_swap_mem = $v->{SizeStoredInPagingFiles};
  my $free_swap_mem = $v->{FreeSpaceInPagingFiles};
  my $used_swap_mem = $total_swap_mem - $free_swap_mem;
  my $used_swap_mem_perc = ($total_swap_mem - $free_swap_mem) / $total_swap_mem * 100;

  printf "Swap total:%d kb\n", $total_swap_mem;
  printf "Swap free:%d kb\n", $free_swap_mem;
  printf "Swap used:%d kb\n", $used_swap_mem;
  printf "Swap used:%.2f %%\n", $used_swap_mem_perc;
}

Note: At 2011-01-19 I've updated this script, since at that time there were no conflicts with posted comments.

回答1:

I suggest you to take a look at this little Perl project:

Check WMI Plus

It's client less, works under Linux and works also with remote Windows machines. I've been using it recently in order to monitor memory usage.



标签: perl wmi