# Configuration $ThresholdAlert = 85 # Email alert threshold $ThresholdRestart = 90 # Restart threshold $CheckInterval = 60 # Check every 60 seconds $LogPath = "C:\MemoryMonitor.log" $SmtpServer = "your.smtp.server.com" $FromAddress = "alert@yourdomain.com" $ToAddress = "admin@yourdomain.com" $SmtpCredential = Get-Credential # Store credentials securely in production # Email body template $EmailSubject = "Memory Alert on $env:COMPUTERNAME" $EmailBody = @" Server: $env:COMPUTERNAME Time: {0} Memory Usage: {1}% Status: {2} "@ function Write-Log { param([string]$Message) Add-Content -Path $LogPath -Value "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') - $Message" } try { while($true) { $MemoryUsage = (Get-Counter '\Memory\% Committed Bytes In Use').CounterSamples.CookedValue $MemoryUsage = [math]::Round($MemoryUsage, 2) if($MemoryUsage -ge $ThresholdRestart) { # Log and restart $Message = "CRITICAL: Memory at ${MemoryUsage}% - Initiating restart" Write-Log $Message Send-MailMessage -From $FromAddress -To $ToAddress -Subject "$EmailSubject - RESTARTING" ` -Body ($EmailBody -f (Get-Date), $MemoryUsage, $Message) ` -SmtpServer $SmtpServer -Credential $SmtpCredential -Priority High Restart-Computer -Force exit } elseif($MemoryUsage -ge $ThresholdAlert) { # Send alert $Message = "WARNING: Memory at ${MemoryUsage}%" Write-Log $Message Send-MailMessage -From $FromAddress -To $ToAddress -Subject "$EmailSubject - WARNING" ` -Body ($EmailBody -f (Get-Date), $MemoryUsage, $Message ` -SmtpServer $SmtpServer -Credential $SmtpCredential } Start-Sleep -Seconds $CheckInterval } } catch { Write-Log "ERROR: $($_.Exception.Message)" exit 1 }