Skip to content

Instantly share code, notes, and snippets.

@randyburden
Created August 3, 2022 13:54
Show Gist options
  • Save randyburden/9f44c732d32978fffe0c7e1d3dad5743 to your computer and use it in GitHub Desktop.
Save randyburden/9f44c732d32978fffe0c7e1d3dad5743 to your computer and use it in GitHub Desktop.
PowerShell script to kill a process when it reaches a certain memory threshold. Writes output to console and a log file.
# Kills a specific Windows Service process if it uses over 80 GB of memory
# Note, be sure to set the Windows Service to restart instantly on failure
# To run this script manually, run the following 2 lines of PowerShell:
# powershell -command "C:\Temp\WindowsScheduledTaskScripts\Kill-Service-At-80-GB.ps1"
# $LASTEXITCODE
# To run as a Windows Scheduled Task:
# Set the program to run as "powershell"
# Set the command to: -Command ". C:\OneDine\WindowsScheduledTaskScripts\Kill-Service-At-80-GB.ps1; exit $LASTEXITCODE"
$maxMemoryInGb = 80;
$processName = "MyProcessName"
$logFilePath = "C:\Temp\WindowsScheduledTaskScripts\Kill-Service-At-80-GB.log"
$processInfo = get-process $processName
$oneGb = 1024 * 1024 * 1024
$memoryUsageInGb = [math]::round($processInfo.WorkingSet64/$oneGb, 2)
$currentDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss";
$output = "$currentDate | Memory Usage: $memoryUsageInGb GB"
$output | Write-Output
$output | Out-File -append -FilePath $logFilePath
if($memoryUsageInGb -gt $maxMemoryInGb){
try {
$output = "$currentDate | Stopping Process: $processName"
$output | Write-Output
$output | Out-File -append -FilePath $logFilePath
Stop-Process -InputObject $processInfo -Force
exit 0
}
catch {
$errorMessage = $error[0].exception.message
$output = "$currentDate | Error Stopping Process: $processName - $errorMessage"
$output | Write-Output
$output | Out-File -append -FilePath $logFilePath
exit 1
}
} else {
exit 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment