gpt4 book ai didi

Powershell 自行更改数组内容

转载 作者:行者123 更新时间:2023-12-04 00:45:47 26 4
gpt4 key购买 nike

我有一段非常简单的代码,应该可以获取原始数据,我需要计算任何 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"

$curr

但是,$prev 中的值在 $curr 之后被重置,如下面的输出所示。第 2 节应与第 1 节相同,但与第 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

最佳答案

Get-Process 返回的[System.Diagnostics.Process] 实例是事件对象,它意味着它们的属性反射(reflect)调用时的进程状态。[1]

因此,假设 wscript 进程集在您的 Get-Process 调用之间没有改变,您将获得指向相同的对象 进程及其属性因此返回相同的值 - 即 then-current 值,例如到目前为止消耗的 CPU 时间。

为避免这种情况,您需要拍摄感兴趣值的快照通过创建[pscustomobject]<最容易做到这一点 通过 Select-Object 克隆进程对象:

$prev = Get-Process -Name "wscript" | Select-Object *

请注意,这会克隆所有 公共(public)属性;为了获得更好的性能,您可能只想使用 Select-Object Id, Name, 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() 反射(reflect)当前值的方法。

关于Powershell 自行更改数组内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53173156/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com