PowerShell实现动态获取当前脚本运行时消耗的内存(powershell脚本语法)干货满满

随心笔谈2年前发布 admin
196 0 0

文章摘要

本文介绍了一个名为 `Get-MemoryUsage` 的 PowerShell 函数,用于监控系统内存使用量的变化。该函数通过调用 `[System.GC]::GetTotalMemory` 获取当前内存使用量,并与上一次记录的值进行比较,计算差异。差异以 Bytes 和 MB 两种形式显示,并通过 `Write-Host` 输出结果。此外,该函数会将当前的内存使用量保存到一个全局变量中,方便后续检查和对比。


#requires -Version 2

$script:last_memory_usage_byte=0

function Get-MemoryUsage
{
$memusagebyte=[System.GC]::GetTotalMemory(‘forcefullcollection’)
$memusageMB=$memusagebyte / 1MB
$diffbytes=$memusagebyte – $script:last_memory_usage_byte
$difftext=”
$sign=”
if ( $script:last_memory_usage_byte -ne 0 )
{
if ( $diffbytes -ge 0 )
{
$sign=’+’
}
$difftext=”, $sign$diffbytes”
}
Write-Host -Object (‘Memory usage: {0:n1} MB ({1:n0} Bytes{2})’ -f $memusageMB,$memusagebyte, $difftext)

# save last value in script global variable
$script:last_memory_usage_byte=$memusagebyte
}

© 版权声明

相关文章