Created
August 26, 2025 11:10
-
-
Save Sy3Omda/498295c1268a40b5df57911b24929156 to your computer and use it in GitHub Desktop.
powershell script to auto restart certain service on 12.00 AM every day
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| $taskName = "Restart-Service" | |
| $serviceName = "ServiceName" # Specify the service name | |
| $scriptPath = "C:\Dir_Name\Restart-Service.ps1" | |
| $logFile = "C:\Dir_Name\Service_Restart_log.txt" | |
| $dirPath = "C:\Dir_Name" | |
| $taskDescription = "Restarts $serviceName daily at 12:00 AM and logs to $logFile" | |
| # Ensure the directory exists | |
| if (-not (Test-Path $dirPath)) { | |
| try { | |
| New-Item -Path $dirPath -ItemType Directory -Force -ErrorAction Stop | |
| Write-Output "Created directory $dirPath" | |
| Add-Content -Path $logFile -Value "[$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')] Created directory $dirPath" | |
| } | |
| catch { | |
| Write-Error "Failed to create directory $dirPath. Error: $($_.Exception.Message)" | |
| exit | |
| } | |
| } | |
| # Validate script path | |
| if (-not (Test-Path $scriptPath)) { | |
| Write-Error "Script file not found at $scriptPath. Task creation aborted." | |
| Add-Content -Path $logFile -Value "[$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')] Error: Script file not found at $scriptPath" | |
| exit | |
| } | |
| # Check if task already exists and remove it | |
| if (Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue) { | |
| Write-Output "Task '$taskName' already exists. Updating task..." | |
| try { | |
| Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -ErrorAction Stop | |
| Add-Content -Path $logFile -Value "[$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')] Removed existing task '$taskName'" | |
| } | |
| catch { | |
| Write-Error "Failed to remove existing task. Error: $($_.Exception.Message)" | |
| Add-Content -Path $logFile -Value "[$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')] Error: Failed to remove task. $($_.Exception.Message)" | |
| exit | |
| } | |
| } | |
| try { | |
| # Create the scheduled task action, passing the service name as an argument | |
| $action = New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "-NoProfile -ExecutionPolicy Bypass -File `"$scriptPath`" -ServiceName `"$serviceName`"" | |
| # Set the trigger to run daily at 12:00 AM (no repetition) | |
| $trigger = New-ScheduledTaskTrigger -Daily -At "12:00 AM" | |
| # Set the principal to run as SYSTEM with highest privileges | |
| $principal = New-ScheduledTaskPrincipal -UserId "SYSTEM" -LogonType ServiceAccount -RunLevel Highest | |
| # Configure task settings for server environment | |
| $settings = New-ScheduledTaskSettingsSet -StartWhenAvailable ` | |
| -ExecutionTimeLimit (New-TimeSpan -Minutes 5) ` | |
| -RestartCount 3 ` | |
| -RestartInterval (New-TimeSpan -Minutes 2) ` | |
| -Priority 7 | |
| # Register the scheduled task | |
| Register-ScheduledTask -TaskName $taskName ` | |
| -Action $action ` | |
| -Trigger $trigger ` | |
| -Principal $principal ` | |
| -Settings $settings ` | |
| -Description $taskDescription ` | |
| -ErrorAction Stop | |
| # Log success | |
| $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss" | |
| Add-Content -Path $logFile -Value "[$timestamp] Scheduled task '$taskName' created successfully for service '$serviceName'." | |
| # Test the task (optional, for verification) | |
| Write-Output "Task created. Testing task execution..." | |
| Start-ScheduledTask -TaskName $taskName | |
| Start-Sleep -Seconds 5 | |
| $taskInfo = Get-ScheduledTaskInfo -TaskName $taskName | |
| Write-Output "Last Run Time: $($taskInfo.LastRunTime)" | |
| Write-Output "Last Task Result: $($taskInfo.LastTaskResult)" | |
| Add-Content -Path $logFile -Value "[$timestamp] Task test executed. Last Run Time: $($taskInfo.LastRunTime), Result: $($taskInfo.LastTaskResult)" | |
| } | |
| catch { | |
| # Log failure | |
| $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss" | |
| Add-Content -Path $logFile -Value "[$timestamp] Failed to create scheduled task. Error: $($_.Exception.Message)" | |
| Write-Error "Failed to create scheduled task. Error: $($_.Exception.Message)" | |
| exit | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment