Can you help me write a PowerShell script for process information?
I would like the output to be in the format of: 20240103 21:29 - pid: 9640 - cpu: 0.1 % - mem: 50 MB - C:\Windows\notepad.exe test1.txt
I have come up with this so far:
$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
}
Output is:
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
It has been a stuggle especially the cpu info.
Can you help me to even more simplify this? Or help me with the mem info?
I have been using Google and ChatGPT. I hope you can help with your expertise.
The main issue is the CPU %: CPU usage is a relative value, updated every millisecond I think, so if you are just looking to make a "Task manager in Powershell" I suggest you to just use NTop(it's also available on Winget ), otherwise I have not found a reliable way to get that info. So I did skip it.
That said: this will return an array with all the info you requested, EXCEPT CPU %, so you can manipulate and format it better to fit your needs (if you find a way to get CPU% you can just add it to the
[PSCustomObject])