This article mainly introduces the PowerShell implementation of dynamic acquisition of the current script running memory consumption, this article directly gives the implementation of script functions, the need for friends can refer to the
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:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23-24 |
#requires-version 2 $script: last_memory_usage_byte = 0 function get-memoryusage {$memusagebyte = [System.gc]::gettot Almemory (' 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 = ' + '} $dif Ftext = ", $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} |
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:
?
1 2 3 4 5 6 7 8 |
ps> get-memoryusage Memory usage:6.7 MB (6,990,328 Bytes) ps> $array = 1..100000 ps> get-memoryusage Memory USAG e:10.2 MB (10,700,064 Bytes, +3709736) ps> remove-variable-name array ps> get-memoryusage Memory MB (7, 792,424 Bytes,-2907640) |