你能帮我写一个获取进程信息的PowerShell脚本吗?
我希望输出的格式为: 20240103 21:29 - pid: 9640 - cpu: 0.1 % - 内存: 50 MB - C:\Windows otepad.exe test1.txt
到目前为止我已经想出了这个:
$app="notepad"
$ids=(Get-Process $app | Select-Object -Property Id) | ForEach-Object {$_.Id}
$date=(Get-Date -format "yyyy-MM-dd HH:mm")
#echo $pids
foreach ($id in $ids) {
# process CPU information
$name = Get-CimInstance -ClassName Win32_PerfRawData_PerfProc_Process -Filter "IDProcess = $id" | Select-Object -ExpandProperty Name
$rawusage = (Get-Counter -Counter "\Process($name)\% Processor Time").CounterSamples.CookedValue
$usage = "{0:F2}" -f $rawusage
# process Mem information
# to be completed
# commandline information
$commandline=((Get-CimInstance Win32_Process -Filter "ProcessId=$id").CommandLine)
echo "$date - pid: $id - cpu: $usage % - command: $commandline"
# write to file
# to be completed
}
输出是:
2024-01-03 23:46 - pid: 2144 - cpu: 0,00 % - command: "C:\Windows\system32\notepad.exe" .\test2.txt
2024-01-03 23:46 - pid: 5796 - cpu: 0,00 % - command: "C:\Windows\notepad.exe" .\test..txt
2024-01-03 23:46 - pid: 7736 - cpu: 0,00 % - command: "C:\Windows\system32\notepad.exe" .\test3.txt
2024-01-03 23:46 - pid: 8156 - cpu: 0,00 % - command: "C:\Windows\system32\notepad.exe" .\test1.txt
这是一个难题,尤其是CPU信息。
你能帮我进一步简化这个吗? 或者帮我获取内存信息?
我一直在使用 Google 和 ChatGPT。 我希望你能用你的专业知识来帮助你。
主要问题是CPU百分比:CPU使用率是一个相对值,我认为每毫秒更新一次,所以如果你只是想在Powershell中制作一个“任务管理器”,我建议你只使用NTop(它也可用)在 Winget 上),否则我还没有找到可靠的方法来获取该信息。所以我就跳过了。
也就是说:这将返回一个包含您请求的所有信息的数组,除了 CPU %,因此您可以更好地操作和格式化它以满足您的需求 (如果你找到了获取 CPU% 的方法,你可以将其添加到
[PSCustomObject]
)
Get-Process -Name $ProcessName | ForEach-Object {
[pscustomobject]@{
Timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm'
ProcessId = $_.Id
MemoryInMB = $_.PrivateMemorySize64 / 1MB
CommandLine = ( Get-CimInstance -ClassName Win32_Process -Filter "ProcessId=$($_.id)").CommandLine
}