Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.2k views
in Technique[技术] by (71.8m points)

powershell - Deep-copy an array

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

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

The solution is to do $d = $c.clone() This isn't working though if the array itself is a collection of reference types. This is my problem. I'm trying to create an array to track CPU usage by creating an array of Processes, wait a while, then check the latest values and calculate the differences. However the Get-Process creates a reference array. So 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 and do it one entry at a time using something like $b[0] = "$a[0].clone()" - PS complains that Clone can't be used in this case.

Any suggestions??

Also, just FYI, the second $a = PS |.... line isn't actually needed since $a is reference type to the PS list object, it actually gets updated and returns the most current values whenever $a is called. I included it to make it clearer what I'm trying to accomplish here.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 particular issue (comparing CPU usage of processes), something more specific would probably be better, as Keith pointed out.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...