To get a rough idea of how much memory a script consumes, or how much memory is consumed when you save a result to a variable in PowerShell, you can use the following function:
#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)
# SA ve last value in script global variable
$script: last_memory_usage_byte = $memusagebyte
}
You can run get-memoryusage at any time, and it will return the memory consumed by the last invocation of the current script, in contrast to the results of your last call to Get-memoryusage, and display the increment of memory.
The key point here is to use GC, which is responsible for garbage collection in. NET framwwork, usually does not immediately release memory, want to calculate the memory consumption roughly, the garbage collector needs to be specified to free unused memory [Gc]::collect (), and then statistics the allocated memory.
To better demonstrate the above function, let's look at an example of an invocation:
ps> get-memoryusage
Memory usage:6.7 MB (6,990,328 Bytes)
ps> $array = 1..100000
ps> Get-memoryusage
Memory usage:10.2 MB (10,700,064 Bytes, +3709736)
ps> remove-variable-name array
PS > Get-memoryusage
Memory usage:7.4 MB (7,792,424 Bytes,-2907640)