远程机器的可用内存百分比

远程机器的可用内存百分比

在阅读 superuser/stackoverflow 时,我无法想出一个脚本来实际输出可用内存百分比(如 Windows 任务管理器中所示)一些远程机器(例如 server1-server4)。这是我的代码,平台应该是 windows,CMD 或 powershell(或类似的东西):

1)CMD,无法获取可用 RAM 的百分比(即无法访问“忙”RAM 来计算“忙/总计 * 100”。来源):
wmic /NODE:"servername" /USER:"yourdomain\administrator" OS GET FreePhysicalMemory

2)powershell(来源),无法获取远程机器的内存(即无法获取Get-WmiObject远程机器的):

$system = Get-WmiObject win32_OperatingSystem
$totalPhysicalMem = $system.TotalVisibleMemorySize
$freePhysicalMem = $system.FreePhysicalMemory
$usedPhysicalMem = $totalPhysicalMem - $freePhysicalMem
$usedPhysicalMemPct = [math]::Round(($usedPhysicalMem / $totalPhysicalMem) * 100,1)

任何帮助表示感谢

答案1

我想出了一个相当通用的脚本,它可以给出可用内存的百分比。要获取已用内存的百分比,只需添加$a=$b-$a

$a=0
$b=0
$strComputer = "localhost"
$a=Get-WmiObject Win32_OperatingSystem -ComputerName $strComputer | fl *freePhysical* | Out-String
$b=Get-WmiObject Win32_OperatingSystem -ComputerName $strComputer | fl *totalvisiblememory* | Out-String
$a = $a -replace '\D+(\d+)','$1'
$b = $b  -replace '\D+(\d+)','$1'
[math]::Round($a/$b*10000)/100

答案2

使用 PowerShell 远程连接 WMI 的方法 https://msdn.microsoft.com/en-us/library/ee309377(v=vs.85).aspx

我已经使用 .NET 来格式化此处的数字示例。 https://technet.microsoft.com/en-us/library/ee692795.aspx

$Servers = @("localhost")

foreach ($Server in $Servers){

$OS = get-wmiobject -Namespace "root\cimv2" -Class Win32_OperatingSystem -Impersonation 3 -computername $Server

foreach ($Item in $OS){
        $RAM = "{0:N6}" -f ($Item.TotalVisibleMemorySize)/1kB
        $FREE = "{0:N6}" -f ($Item.FreePhysicalMemory)/1kB
        $Server + "`t" + "{0:P0}" -f ($FREE/$RAM)
        }
}

编辑

要解决 PS 和 .net 版本之间的数字格式问题,您可以使用十进制或定点格式而不是数字来纠正。https://docs.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings#the-decimal-d-format-specifier

$Servers = @("localhost")

foreach ($Server in $Servers){

$OS = get-wmiobject -Namespace "root\cimv2" -Class Win32_OperatingSystem -Impersonation 3 -computername $Server

foreach ($Item in $OS){
        $RAM = "{0:D6}" -f ($Item.TotalVisibleMemorySize)/1kB
        $FREE = "{0:D6}" -f ($Item.FreePhysicalMemory)/1kB
        $Server + "`t" + "{0:P0}" -f ($FREE/$RAM)
        }
}

或者

$Servers = @("localhost")

foreach ($Server in $Servers){

$OS = get-wmiobject -Namespace "root\cimv2" -Class Win32_OperatingSystem -Impersonation 3 -computername $Server

foreach ($Item in $OS){
        $RAM = "{0:F6}" -f ($Item.TotalVisibleMemorySize)/1kB
        $FREE = "{0:F6}" -f ($Item.FreePhysicalMemory)/1kB
        $Server + "`t" + "{0:P0}" -f ($FREE/$RAM)
        }
}

相关内容