Situatie
Putem face un script in powershell care sa opreasca anumite servicii in momentul in care ajung sa consume mai multe resurse ram decat ar fi in regula.
Solutie
# Functie pentru a obtine utilizarea totala a memoriei RAM
function Get-MemoryUsage {
$memory = Get-CimInstance Win32_OperatingSystem
$totalPhysicalMemory = $memory.TotalVisibleMemorySize
$freePhysicalMemory = $memory.FreePhysicalMemory
$usedMemory = $totalPhysicalMemory – $freePhysicalMemory
$memoryUsage = [math]::Round(($usedMemory / $totalPhysicalMemory) * 100, 2)
return $memoryUsage
}
# Functie pentru a opri un serviciu specificat de utilizator
function Stop-SpecifiedService {
param (
[string]$serviceName
)
if (Get-Service -Name $serviceName -ErrorAction SilentlyContinue) {
Stop-Service -Name $serviceName -Force
Write-Host “Service $serviceName stopped.”
} else {
Write-Host “Service $serviceName not found.”
}
}
# Cere utilizatorului numele serviciului care sa fie oprit
$serviceToStop = Read-Host “Enter the name of the service to stop if memory usage exceeds 80%”
# Monitorizeaza utilizarea memoriei RAM si opreste serviciul specificat de utilizator cand depaseste 80%
while ($true) {
$memoryUsage = Get-MemoryUsage
Write-Host “Memory Usage: $memoryUsage%”
if ($memoryUsage -ge 40) {
Write-Host “High memory usage detected. Stopping service $serviceToStop.”
Stop-SpecifiedService -serviceName $serviceToStop
}
Start-Sleep -Seconds 60
}
Leave A Comment?