【发布时间】:2020-03-21 15:58:04
【问题描述】:
我想使用 powershell 来返回值,喜欢任务管理器。
但是,网络使用项无法正确返回。
如何修改代码?非常感谢。
$RAM= Get-WMIObject Win32_PhysicalMemory | Measure -Property capacity -Sum | %{$_.sum/1Mb}
$cores = (Get-WmiObject Win32_Processor).NumberOfLogicalProcessors
while ($true) {
$tmp = Get-WmiObject Win32_PerfFormattedData_PerfProc_Process |
select-object -property Name, @{Name = "CPU"; Expression = {($_.PercentProcessorTime/$cores)}}, @{Name = "PID"; Expression = {$_.IDProcess}}, @{"Name" = "Memory(MB)"; Expression = {[int]($_.WorkingSetPrivate/1mb)}}, @{"Name" = "Memory(%)"; Expression = {([math]::Round(($_.WorkingSetPrivate/1Mb)/$RAM*100,2))}}, @{Name="Disk(MB)"; Expression = {[Math]::Round(($_.IODataOperationsPersec / 1mb),2)}}, @{"Name"="Network"; Expression = {get-counter "\Process($_.Name)\IO Read Bytes/sec"}} |
Where-Object {$_.Name -notmatch "^(idle|_total|system)$"} |
Sort-Object -Property CPU -Descending|
Select-Object -First 5;
cls
$tmp | Format-Table -Autosize -Property Name, CPU, PID, "Memory(MB)", "Memory(%)", "Disk(MB)", "Network";
Start-Sleep 3
}
此代码根据文章修改如下:
1.CPU and memory usage in percentage for all processes in Powershell
2.https://superuser.com/questions/1314534/windows-powershell-displaying-cpu-percentage-and-memory-usage#new-answer?newreg=a9290345d72946db9c7f8fd2af10de0a
3.Powershell Script - list process with cpu, memory, disk usage
我添加了一个变量 $process 来显示每个进程的所有者,但是缺少一些参数。我从微软找不到任何关于 Get-WmiObject Win32_PerfFormattedData_PerfProc_Process 的文档,这正常吗?修改后的代码如下:
$RAM= Get-WMIObject Win32_PhysicalMemory | Measure -Property capacity -Sum | %{$_.sum/1Mb}
$cores = (Get-WmiObject Win32_Processor).NumberOfLogicalProcessors
$Process = Get-Wmiobject Win32_process -computername "myComputerName" | select *,@{Name='Owner';Expression={($_.GetOwner()).User}}
while ($true) {
$tmp = Get-WmiObject Win32_PerfFormattedData_PerfProc_Process |
select-object -property Name, @{Name = "CPU"; Expression = {($_.PercentProcessorTime/$cores)}}, @{Name = "PID"; Expression = {$_.IDProcess}}, @{"Name" = "Memory(MB)"; Expression = {[int]($_.WorkingSetPrivate/1mb)}}, @{"Name" = "Memory(%)"; Expression = {([math]::Round(($_.WorkingSetPrivate/1Mb)/$RAM*100,2))}}, @{Name="Disk(MB)"; Expression = {[Math]::Round(($_.IODataOperationsPersec / 1mb),2)}}, @{"Name"="Network"; Expression = { $_.IOReadBytesPersec }}, @{Name="Username"; Expression = {($($Process | ?{$_.ProcessId -eq $Item.IDProcess})).Owner} |
Where-Object {$_.Name -notmatch "^(idle|_total|system)$"} |
Sort-Object -Property CPU -Descending|
Select-Object -First 15;
cls
$tmp | Format-Table -Autosize -Property Name, CPU, PID, "Memory(MB)", "Memory(%)", "Disk(MB)", "Network", "Username";
Start-Sleep 1
}
修改部分引用自https://powershell.org/forums/topic/getting-percentage-cpu-time-and-owner-for-processes/
【问题讨论】:
标签: powershell