PowerShell dynamically obtains the memory consumed by the current script
This article mainly introduces how PowerShell can dynamically obtain the memory consumed by the current script running. This article describes how to implement the script function. For more information, see
To roughly understand how much memory a script consumes, or how much memory you consume when saving the 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]: GetTotalMemory ('forcefullcollect ') $ MemusageMB = $ memusagebyte/1 MB $ 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 } |
You can run Get-MemoryUsage at any time. It will return the memory consumed after the last call of the current script, and compare it with the running result of the last call of Get-MemoryUsage, and display the memory increment.
The key point here is that GC is used. NET Framwwork is responsible for garbage collection, usually does not immediately release the memory, to roughly calculate the memory consumption, the garbage collector needs to be specified to release unused memory [gc]: Collect (), then count the allocated memory.
To better demonstrate the above functions, let's look at a call example:
?
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 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) |