Powershell自行更改阵列内容
我有一段非常简单的代码,用来获取计算wscript进程在过去30秒内使用的CPU秒数所需的原始数据Powershell自行更改阵列内容,powershell,properties,Powershell,Properties,我有一段非常简单的代码,用来获取计算wscript进程在过去30秒内使用的CPU秒数所需的原始数据 $prev=Get-Process | Where-Object { $_.Name -eq "wscript" } $prev start-sleep -Seconds 30 $curr=Get-Process | Where-Object { $_.Name -eq "wscript" } echo "section 2" $prev echo "section 3" $cu
$prev=Get-Process | Where-Object { $_.Name -eq "wscript" }
$prev
start-sleep -Seconds 30
$curr=Get-Process | Where-Object { $_.Name -eq "wscript" }
echo "section 2"
$prev
echo "section 3"
$curr
但是,$prev中的值在$curr之后被重置,如下面的输出所示。第2节应与第一节相同,但与第3节相匹配
Handles NPM(K) PM(K) WS(K) CPU(s) Id SI ProcessName
------- ------ ----- ----- ------ -- -- -----------
177 19 2640 9252 1,795.55 12308 1 wscript
177 19 2628 9340 1,799.67 17316 1 wscript
177 19 2652 9292 1,803.83 25248 1 wscript
section 2
177 19 2640 9252 1,825.28 12308 1 wscript
177 19 2628 9340 1,829.42 17316 1 wscript
177 19 2652 9292 1,833.53 25248 1 wscript
section 3
177 19 2640 9204 1,825.28 12308 1 wscript
177 19 2628 9296 1,829.42 17316 1 wscript
177 19 2652 9264 1,833.55 25248 1 wscript
获取过程返回的[System.Diagnostics.Process]
实例是活动对象,这意味着它们的属性反映调用时的进程状态。[1]
因此,假设wscript
进程集在Get Process
调用之间没有更改,则会得到指向相同进程的对象,因此它们的属性返回相同的值,即当前值,例如到目前为止消耗的CPU时间。
为了避免这种情况,您需要拍摄感兴趣的值的快照,通过选择对象创建[pscustomobject]
过程对象克隆,这是最容易做到的:
$prev = Get-Process -Name "wscript" | Select-Object *
请注意,这将克隆所有公共属性;为了获得更好的性能,您可能只需要克隆感兴趣的值,例如,选择对象Id、名称、CPU
另外,请注意我如何消除了对Where Object
的需要,因为您可以使用Get Process-name
简单地查找具有给定名称的进程
要计算所消耗CPU时间的差异,可以使用以下方法:
# Get the processes...
$processes = Get-Process "wscript"
# ... and create snapshot objects for them.
$processesSnapshot = $processes | Select-Object *
start-sleep -Seconds 30
# Create objects that contain the delta (difference) in CPU
# time elapsed, by comparing the .CPU values from the live objects
# to that of the snapshots.
$i = 0
$CpuDeltas = foreach ($process in $processes) {
$processSnapshot = $processesSnapshot[$i++]
# Clone the snapshot object and add a property reflecting the CPU-consumption
# delta and output it.
$processSnapshot | Select-Object *, @{ n='CpuDelta'; e={ $process.CPU - $_.CPU } }
}
# Output for display.
$CpuDeltas | Format-Table Id, Name, CpuDelta
[1] 一些属性(如.MainWindowTitle
)被缓存,需要调用.Refresh()
方法来反映当时的当前值。很高兴听到这个消息,@dazedandMiddle;我的荣幸。