【问题标题】:Performance Counter on how much Physical Memory % Used in Power shellPowershell 中使用的物理内存百分比的性能计数器
【发布时间】:2020-05-22 06:31:25
【问题描述】:

我正在尝试使用 power shell 中的性能计数器监控本地计算机的物理内存使用百分比。在资源监视器中,在内存选项卡下,我们可以了解使用了多少物理内存。同样在任务管理器中,在性能选项卡-> 内存下,我们可以查看使用了多少内存。检查图片以获取参考。

我在 power shell 中按照以下步骤来实现相同的结果

1) 使用下面的命令,我得到了最大的物理内存

 $totalPhysicalmemory = gwmi Win32_ComputerSystem | % {$_.TotalPhysicalMemory /1GB}

2) 使用下面的计数器命令,我得到平均可用内存

 $avlbleMry = ((GET-COUNTER -Counter "\Memory\Available MBytes"|select -ExpandProperty countersamples | select -ExpandProperty cookedvalue )/1GB

3) 计算使用的物理内存百分比:(将数学四舍五入到小数点后 2 位)

 (($totalPhysicalmemory-$avlbleMry)/$totalPhysicalmemory)*100

我做得对吗?这是获取已用内存百分比的正确方法吗?有没有更好的方法来使用 WMI 命令或性能计数器或其他方式来获取物理内存的百分比?

【问题讨论】:

    标签: powershell wmi monitoring performancecounter wmi-service


    【解决方案1】:

    我认为你的方法是对的,但是内存单元是错误的。

    另外,using Get-CimInstance is recommended

    所以代码是这样的

    # use the same unit `/1MB` and `Available MBytes`
    $totalPhysicalmemory = (Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory /1MB
    $avlbleMry = (Get-Counter -Counter "\Memory\Available MBytes").CounterSamples.CookedValue
    (($totalPhysicalmemory-$avlbleMry)/$totalPhysicalmemory)*100
    

    还有其他一些方法

    # Win32_OperatingSystem, KB
    $osInfo = Get-CimInstance -ClassName Win32_OperatingSystem
    $total = $osInfo.TotalVisibleMemorySize
    $free = $osInfo.FreePhysicalMemory
    $used = $total - $free
    $usedPercent =  $used/$total * 100
    echo $usedPercent
    
    # Microsoft.VisualBasic, bytes
    Add-Type -AssemblyName Microsoft.VisualBasic
    $computerInfo = [Microsoft.VisualBasic.Devices.ComputerInfo]::new()
    $total = $computerInfo.TotalPhysicalMemory
    $free = $computerInfo.AvailablePhysicalMemory
    $used = $total - $free
    $usedPercent =  $used/$total * 100
    echo $usedPercent
    

    【讨论】:

    • 拥有 [math]::round() 是加号以获得最短的十进制值。无论如何,答案被接受。谢谢:)
    猜你喜欢
    • 2014-12-08
    • 1970-01-01
    • 2010-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多