Deep copy array

I hit my head against the wall on this one. I know that if I create an Array in Powershell, then copy the array, it will copy it as a reference type, not a value type.
So a classic example:

$c = (0,0,0) $d = $c $c[0] = 1 $d 1 0 0 

The solution is to make $d = $c.clone() This does not work, although the array itself is a collection of reference types. That's my problem. I am trying to create an array to track CPU usage by creating an array of processes, wait a while, and then check the latest values ​​and calculate the differences. However, Get-Process creates a reference array. Therefore, when I do the following:

 $a = ps | sort -desc id | where-object {$_.CPU -gt 20} #Get current values $b = $a.clone() #Create a copy of those values. sleep 20 #Wait a few seconds for general CPU usage... $a = ps | sort -desc id | where-object {$_.CPU -gt 20} #Get latest values. $a[0] $b[0] #returns the same value as A. Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessNam ------- ------ ----- ----- ----- ------ -- ---------- 3195 57 90336 100136 600 83.71 7244 OUTLOOK 

$a and $b will always return the same value. If I try to make one record at a time using something like $ b [0] = "$ a [0] .clone ()" - PS complains that the clone cannot be used in this case.

Any suggestions

Also, only FYI, the second line $a = PS |.... is not actually needed, since $a is the reference type for the PS list object, it is actually updated and returns the most recent values ​​whenever $a called. I have included it to clarify what I am trying to accomplish here.

+3
source share
2 answers

To copy an array, you can do the following:

 $c = (0,0,0) $d = $c | foreach { $_ } $c[0] = 1 "c is [$c]" "d is [$d]" 

Result

 c is [1 0 0] d is [0 0 0] 

For your specific problem (comparing processor usage by processes), a more specific one would probably be better, as Kate pointed out.

+5
source

Technically, $d = $c not any copy of an array (reference or value). It just captures the reference to the array $ c, refers to $ d. I think you only need to capture an array of processes once and then call the Refresh method. First you need to check the Exited property to make sure the related process is still running. Of course, this will not help you if you are interested in any new process that starts. In this case, take a snapshot of the processes at different times, filter out everything except the intersection of the processes between the two arrays (according to the process Id), and then calculate the differences in their property values ​​- again based on the process ID. Make it simpler, you can put each snapshot in a hash table using a process id.

+1
source

Source: https://habr.com/ru/post/1268687/


All Articles