CPU Usage I Get-Counter: The specified object was not found on the computer.

Tyrone Hirt 41 Reputation points
2022-12-02T15:44:59.167+00:00

I'm trying to get the CPU usage for a process with a PowerShell script, but I get the message

Get-Counter: The specified object was not found on the computer.  

The script I'm using is this one:

# To get the PID of the process (this will give you the first occurrance if multiple matches)  
$proc_pid = (get-process "slack").Id[0]  
  
# To match the CPU usage to for example Process Explorer you need to divide by the number of cores  
$cpu_cores = (Get-WMIObject Win32_ComputerSystem).NumberOfLogicalProcessors  
  
# This is to find the exact counter path, as you might have multiple processes with the same name  
$proc_path = ((Get-Counter "\Process(*)\ID Process").CounterSamples | ? {$_.RawValue -eq $proc_pid}).Path  
  
# We now get the CPU percentage  
$prod_percentage_cpu = [Math]::Round(((Get-Counter ($proc_path -replace "\\id process$","\% Processor Time")).CounterSamples.CookedValue) / $cpu_cores)  

It was taken from this thread:
How to get CPU usage & Memory consumed by particular process in powershell script

I believe the error is because my Windows is in Brazilian Portuguese, however I couldn't find the equivalent of the term ID process in Brazilian Portuguese.

What I want the script to do:
I want to extract the processing usage of a specific process and if it is less than 5% I want it to be terminated.

Any idea how I can make this work?

Windows 11
Windows 11
A Microsoft operating system designed for productivity, creativity, and ease of use.
10,168 questions
Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,576 questions
0 comments No comments
{count} votes

4 answers

Sort by: Most helpful
  1. Rich Matheisen 47,466 Reputation points
    2022-12-02T16:53:24.343+00:00

    Why not create a PerfMon basic collection set to use the "Process" counter for "slack" and find the localized property name for "ID Process" in the list of properties. Have the collection set saved to a file (a tab separated file is easy to read), and let it run for a few seconds. Stop the collection and open the file and the correct name should be found on the 1st line.

    1 person found this answer helpful.
    0 comments No comments

  2. Rich Matheisen 47,466 Reputation points
    2022-12-03T16:34:50.507+00:00

    What do you want to happen if the process name isn't found? There's no loop in your code so I'm assuming the errors after the one thrown by Get-Process are from the two Get-Counter cmdlets?

    If you just want to send a message to the console when the Get-Process fails, then try something like this:

    # To get the PID of the process (this will give you the first occurrance if multiple matches)  
    Try{   
        $proc_pid = (get-process "slack" -ErrorAction STOP).Id[0]  
          
        # To match the CPU usage to for example Process Explorer you need to divide by the number of cores  
        $cpu_cores = (Get-WMIObject Win32_ComputerSystem).NumberOfLogicalProcessors  
         
        # This is to find the exact counter path, as you might have multiple processes with the same name  
        $proc_path = ((Get-Counter "\Processo(slack)\% tempo de processador").CounterSamples | ? {$_.RawValue -eq $proc_pid}).Path  
         
        $prod_percentage_cpu = [Math]::Round(((Get-Counter "\Processo(slack)\% tempo de processador").CounterSamples.CookedValue) / $cpu_cores)  
         
        Write-Host $prod_percentage_cpu  
    }  
    Catch{  
        Write-Host "No process was found" -ForegroundColor Red  
    }  
    

    I'd be cautious about using the cooked value when you check for activity. The RawValue may be small enough that the rounding from a UINT64 to a Double type will produce a value of zero. Remember, you're getting a one-time counter value, not a cumulative one. You may be able to avoid using PerfMon counters and just use the TotalProcessorTime or UserProcessorTime values from the Get-Process to accomplish what you need.

    1 person found this answer helpful.

  3. Tyrone Hirt 41 Reputation points
    2022-12-02T17:39:45.013+00:00

    Thank you for your help!

    To be honest, I don't exactly know how to do what you suggested, however I modified the Script and it seems to work:

    # To get the PID of the process (this will give you the first occurrance if multiple matches)  
    $proc_pid = (get-process "slack").Id[0]  
      
    # To match the CPU usage to for example Process Explorer you need to divide by the number of cores  
    $cpu_cores = (Get-WMIObject Win32_ComputerSystem).NumberOfLogicalProcessors  
      
    # This is to find the exact counter path, as you might have multiple processes with the same name  
    $proc_path = ((Get-Counter "\Processo(slack)\% tempo de processador").CounterSamples | ? {$_.RawValue -eq $proc_pid}).Path  
      
    $prod_percentage_cpu = [Math]::Round(((Get-Counter "\Processo(slack)\% tempo de processador").CounterSamples.CookedValue) / $cpu_cores)  
      
    Write-Host $prod_percentage_cpu  
    

    It turned out like this, but I don't know if it's optimized in the best way...
    What do you think?

    Now I'm thinking of creating an IF conditional like:

    if ($prod_percentage_cpu -lt 10) {  
    kill taskkill /IM slack.exe -f  
    }  
    

    Thank you very much for your attention!


  4. Tyrone Hirt 41 Reputation points
    2022-12-03T16:59:37.87+00:00

    In the meantime I found a solution by setting up the script like this:

     # Close Media Encoder if crash  
     $Processo = "Adobe Media Encoder"   
     # This line of code asks to return $true (bool, since Get-Process does not return $True or $False, but a list) if the process in $Process exists, if it is $true, it allows the execution of the other actions.  
     If (([bool](Get-Process $Processo -EA SilentlyContinue)) -eq $true) {  
       
     # To get the PID of the process (this will give you the first occurrance if multiple matches)  
     $proc_pid = (get-process $Processo -EA SilentlyContinue).Id[0]  
          
     # To match the CPU usage to for example Process Explorer you need to divide by the number of cores  
     $cpu_cores = (Get-WMIObject Win32_ComputerSystem).NumberOfLogicalProcessors  
          
     # This is to find the exact counter path, as you might have multiple processes with the same name  
     $proc_path = ((Get-Counter "\Processo($Processo)\% tempo de processador" -ErrorAction SilentlyContinue).CounterSamples | ? {$_.RawValue -eq $proc_pid} -ErrorAction SilentlyContinue).Path  
          
     $prod_percentage_cpu = [Math]::Round(((Get-Counter "\Processo($Processo)\% tempo de processador" -ErrorAction SilentlyContinue).CounterSamples.CookedValue) / $cpu_cores)  
       
     # Variables to check if there are any incomplete renders in the render folder  
     $RenderFolder = "C:\Users\MyUser\Desktop\Test\Render"  
     $IncompleteRender = ForEach-Object { Get-ChildItem $_$RenderFolder -Recurse | Where-Object { ($_.Extension -eq ".m4v")}  | Select-Object -ErrorAction SilentlyContinue}     
       
     if (($prod_percentage_cpu -lt 5) -and ($IncompleteRender)) {   
       
     taskkill /IM "$Processo.exe" -f  
     Write-Host -ForegroundColor White "$Processo foi finalizado"  
     } }  
     # Close MediaEncoder if crash  
    

    I don't know if this solution that I created is the best, I'm a beginner and I'm trying hard to learn, but precisely because I don't have much knowledge in PowerShell, I may be going around a lot...

    Sorry, I had to create a new answer because the script is big.

    Thank you very much for your help and attention!

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.