Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # === CONFIGURATION ===
- $exePath = "Your\Path\Here" # Full path to the specific .exe
- $threshold = 10 # CPU % threshold
- $duration = 20 # Seconds of low CPU required to kill
- $intervalMs = 1000 # Interval in milliseconds
- $lowCpuCount = 0
- # Helper: find process by full exe path
- function Get-TargetProcess {
- return Get-Process | Where-Object {
- $_.Path -and ($_.Path -ieq $exePath)
- } | Select-Object -First 1
- }
- Write-Host "Monitoring processes with path: $exePath"
- # Timer setup
- $stopwatch = [System.Diagnostics.Stopwatch]::StartNew()
- while ($true) {
- # Get the target process
- $targetProc = Get-TargetProcess
- if (-not $targetProc) {
- Write-Host "No process found with path: $exePath"
- Start-Sleep -Seconds 2 # Delay before trying again
- continue
- }
- $targetPid = $targetProc.Id
- $processName = $targetProc.Name
- Write-Host "`nMonitoring process: $exePath (PID: $targetPid)"
- # Reset CPU counter
- $lowCpuCount = 0
- while ($true) {
- $loopStart = $stopwatch.ElapsedMilliseconds
- try {
- $proc = Get-Process -Id $targetPid -ErrorAction Stop
- $counterPath = "\Process($processName)\% Processor Time"
- $cpuRaw = (Get-Counter $counterPath).CounterSamples[0].CookedValue
- $cores = (Get-CimInstance Win32_ComputerSystem).NumberOfLogicalProcessors
- $cpu = [math]::Round($cpuRaw / $cores, 2)
- if ($cpu -lt $threshold) {
- $lowCpuCount++
- Write-Host "[$(Get-Date -f 'HH:mm:ss')] CPU LOW: $cpu% ($lowCpuCount / $duration)"
- } else {
- $lowCpuCount = 0
- Write-Host "[$(Get-Date -f 'HH:mm:ss')] CPU OK: $cpu%"
- }
- if ($lowCpuCount -ge $duration) {
- Write-Host "`nKilling process $processName (PID: $targetPid)..."
- Stop-Process -Id $targetPid -Force
- break # Exit the inner while loop and continue monitoring for new processes
- }
- } catch {
- Write-Host "Process not found. Searching for new process..."
- break # Process has exited, break and continue searching
- }
- # Timing control: wait exactly 1000ms per loop
- $loopElapsed = $stopwatch.ElapsedMilliseconds - $loopStart
- $sleepTime = $intervalMs - $loopElapsed
- if ($sleepTime -gt 0) {
- Start-Sleep -Milliseconds $sleepTime
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement