问题描述
我一直在把头撞在墙上.
我知道,如果我在Powershell中创建一个数组,然后复制该数组,它将把它复制为引用类型而不是值类型.
因此,经典示例是:
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
解决方案是执行$d = $c.clone()
如果数组本身是引用类型的集合,则此方法不起作用.这是我的问题.我正在尝试通过创建一个进程数组来创建一个数组来跟踪CPU使用率,请稍等片刻,然后检查最新值并计算差异.但是,Get-Process会创建一个引用数组.因此,当我执行以下操作时:
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
和$b
将始终返回相同的值.如果我尝试使用$ b [0] ="$ a [0] .clone()"来一次输入一个条目-PS抱怨在这种情况下不能使用Clone.
$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.
有什么建议吗?
此外,仅供参考,由于$a
是PS列表对象的引用类型,因此实际上并不需要第二条$a = PS |....
行,只要调用$a
,它实际上就会更新并返回最新的值.我包括了它,以使我在这里想要完成的工作更清楚.
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.
推荐答案
要复制数组,可以执行以下操作:
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]"
结果
c is [1 0 0]
d is [0 0 0]
对于您的特定问题(比较进程的CPU使用率),正如Keith指出的那样,更具体一些可能会更好.
For your particular issue (comparing CPU usage of processes), something more specific would probably be better, as Keith pointed out.
这篇关于深度复制阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!