IIS (Internet Information Services) servers may occasionally experience memory leaks or stuck worker processes in high-traffic or older web setups. The server will stay responsive without human interaction if a periodic refresh is automated. This post offers a thorough tutorial on how to write a PowerShell maintenance script and use Windows Task Scheduler to schedule it.

Phase 1: Creating the PowerShell Script
The goal of the script is to refresh Application Pools and restart core services without requiring user interaction.

Create the Directory: Create a folder named C:\IISScripts\ to store your automation files.
The Script: Create a file named Restart-IIS.ps1 with the following content:
# Import the IIS Module
Import-Module WebAdministration

# 1. Recycle all Application Pools
# This clears memory for individual apps without stopping the whole server
Get-ChildItem IIS:\AppPools | ForEach-Object { Restart-WebAppPool -Name $_.Name }

# 2. Perform a full IIS Reset
# Restarts the W3SVC and other core services
iisreset /restart /timeout:20

# 3. Ensure all sites are started
# Restarts any sites that may have been manually stopped
Get-Website | Where-Object { $_.State -ne "Started" } | Start-Website


Note on Permissions: When testing this script manually in PowerShell ISE, you must right-click the program and select Run as Administrator. Failure to do so will result in "Access Denied" errors, even if your account has admin rights.

Phase 2: Configuring Task Scheduler
To run this every 5 hours automatically, use the Windows Task Scheduler with specific security settings to prevent "Logon Session" errors.

1. General Settings

 

  • Name: IIS 5-Hour Refresh.
  • Security Options: Click Change User or Group and set it to SYSTEM.
  • Privileges: Check Run with highest privileges.
  • Logon Options: Select Run whether user is logged on or not.

2. Triggers
Set the trigger to One time.
Under Advanced Settings, check Repeat task every: 5 hours.
Set duration to Indefinitely.

3. Actions

  • Action: Start a program.
  • Program/script: powershell.exe.
  • Add arguments: -ExecutionPolicy Bypass -File "C:\IISScripts\Restart-IIS.ps1".

Phase 3: Verification and Troubleshooting
Once configured, you should confirm the automation is working correctly:

  • Task Success: In the Task Scheduler Library, the Last Run Result should show 0x0.
  • System Logs: Open Event Viewer and navigate to Windows Logs > System. Look for a log entry with the source IIS-IISReset.
  • Common Error: If you see "A specified logon session does not exist," ensure the task is running under the SYSTEM account rather than a specific user account.

By following these steps, your IIS server will automatically refresh its resources every 5 hours, ensuring high availability and system stability.