Tools and Methods to Automate Server Scripts

When it comes to Windows script automation, there are several tools and methods you can use to make all these repetitive tasks completely automatic. However, the tools and methods you would need to use heavily depend on the process you must automate and the way you would like to approach these tasks.

Let’s go over the main methods for Windows automation:

Task Scheduler

The Task Scheduler is a built-in Windows tool that allows administrators to automate tasks and run any specific scripts at exact times. The Windows scheduler is an amazing graphical interface tool for setting up routines ranging from system restarts to deleting files or launching custom-built PowerShell scripts.

As an administrator, you can set up defined triggers, permissions, and conditions, making the scheduler one of the widely preferred methods for automation on any Windows distribution.

PowerShell

PowerShell is a scripting language, created specifically for system administration, and is the foundation of Windows automation. Unlike the scheduler, PowerShell is not limited in any way, and IT professionals can easily execute multiple commands at once, manage Active Directory, create/delete user accounts, automate SharePoint Online tasks using “Connect-SPOService“, monitor utilization, and even handle software deployment remotely.

We can’t express the capabilities of Windows PowerShell in a few sentences, but a bit later, we’re going to provide you with an in-depth PowerShell automation guide.

Windows Services

A more of a method, rather than a tool, would be Windows Services, whenever you need a script to run 24/7, instead of on a schedule. Using Windows services to automate tasks is excellent for processes you need running, even when no one is logged in. This involves maintenance, process monitoring, or configuration management and is commonly applied in IT environments.

Here’s an easy-to-scan summary:

Tool/Method:User For:Difficulty:Requirement:
Task SchedulerDeploying scheduled scripts and automatic backups.EasyBuilt-in
PowerShellHandling complex automation and API integration.ModeratePowerShell 5.1+
Windows ServicesContinuous background processes deployment.AdvancedDevelopment skills

See Also: How to Simplify IT Tasks with PowerShell Automation

Windows Task Scheduler: Automate Tasks With GUI

The Task Scheduler is the most basic, yet very effective way to automate tasks on a Windows server, allowing you to run programs and scripts automatically.

Here are the main Task Scheduler components:

Component:What It Means:Practical Examples:
TriggersWhen the Task RunsSpecific Time, On Startup, On Event
ActionsWhat the Task DoesRun Script, Show Text, Send Email
ConditionsAdditional RequirementsRun Only When Idle, Save Power
SettingsThe Task BehaviorEmergency Reboot, Run S

It’s completely normal to get lost, especially if you have never used Task Scheduler before, so let’s move on and learn how to create a schedule through the GUI.

A decorative image illustrating the Windows Task Scheduler.

Creating Task (GUI):

To help you understand how the scheduler works, we’re going to teach you how to do a simple task that will automatically run a PowerShell script every day at 3 AM.

Here’s how it goes:

1. Click the Start Menu, type “Task Scheduler“, and open it.

2. Then, select the “Action” tab and choose “Create Task

A informational image showing how to "Create a Task" in Windows Task Scheduler.

3. Next, provide your task with a NAME for easier recognition.

A informational image showing how to name a task in Windows Task Scheduler.

4. In the “Trigger” tab, choose “Daily” and set a Start Time.

A informational image showing how to schedule a trigger in Windows Task Scheduler.

5. In the “Actions” tab, select “Start a program” and choose a script.

A informational image showing how to run a PowerShell script through Windows Task Scheduler.

The final step here is to select a script. Let’s say, for example, you have a PowerShell backup script. In that case, under “Program” you must select “powershell.exe” and for “Arguments” you must pinpoint the exact location of the script file. For instance, “-File “C:\Scripts\Backup.ps1“.

That’s it. If the script is correct, your Windows server will perform automatic updates every day at 3 AM.

Creating Tasks with PowerShell:

Now that you have mastered creating tasks with the graphical user interface of the Task Scheduler, you can experiment and achieve some surface-level automation. However, if you want to take your automated tasks one step further, you need to explore PowerShell automation and how to deploy it.

Note: All of this works without the need to install software!

A decorative image showing the Windows PowerShell logo.

Define the Action

The first step is to tell Windows exactly what the task should do. In the example below, we’re going to tell Windows to run a specific PowerShell script (the one we’ve used earlier, “Backup.ps1” in C:\Scripts).

$action = New-ScheduledTaskAction -Execute "PowerShell.exe" `
    -Argument "-File C:\Scripts\Backup.ps1"

Set the Trigger

Same as with the Task Scheduler, the next step is to set a trigger, hence instruct Windows exactly when it should run the previously pinpointed script.

$trigger = New-ScheduledTaskTrigger -Daily -At 2:00AM

Set the Principal

Here’s where things start to differ from the Task Scheduler and go to a deeper level.

This part defines which account the task should run under, and you can use Get-Credential to securely provide the necessary credentials.

$principal = New-ScheduledTaskPrincipal -UserId "SYSTEM" `
    -LogonType ServiceAccount -RunLevel Highest

Here’s how all the parts of a scheduled task come together in PowerShell:

$action = New-ScheduledTaskAction -Execute "PowerShell.exe" `
    -Argument "-File C:\Scripts\Backup.ps1"

$trigger = New-ScheduledTaskTrigger -Daily -At 2:00AM

$principal = New-ScheduledTaskPrincipal -UserId "SYSTEM" `
    -LogonType ServiceAccount -RunLevel Highest

Here’s a simple explanation:

  • Action: Tells the computer what to run, in this case, your PowerShell script.
  • Trigger: Determines exactly when the scheduled task/script will execute.
  • Principal: Outlines the permissions and account used for this automation.

Common PowerShell Triggers

Now that we understand the basics, let’s take a look at some specific ways to define your triggers to get even more flexibility when it comes to scheduling.

# Daily at a specific time
$trigger = New-ScheduledTaskTrigger -Daily -At "3:00AM"

# Weekly on specific days
$trigger = New-ScheduledTaskTrigger -Weekly -DaysOfWeek Monday,Friday -At "6:00PM"

# At system startup
$trigger = New-ScheduledTaskTrigger -AtStartup

# On user logon
$trigger = New-ScheduledTaskTrigger -AtLogOn

# Every 15 minutes
$trigger = New-ScheduledTaskTrigger -Once -At (Get-Date) `
    -RepetitionInterval (New-TimeSpan -Minutes 15) `
    -RepetitionDuration ([TimeSpan]::MaxValue)

Managing Scheduled Tasks

In addition to the advanced scheduling possible through PowerShell, there is also a way to check, run, control state, and export tasks after they have been created.

# List all scheduled tasks
Get-ScheduledTask

# Get details for a specific task
Get-ScheduledTask -TaskName "Daily Backup"

# Run a task immediately
Start-ScheduledTask -TaskName "Daily Backup"

# Disable a task temporarily
Disable-ScheduledTask -TaskName "Daily Backup"

# Enable a previously disabled task
Enable-ScheduledTask -TaskName "Daily Backup"

# Remove a task permanently
Unregister-ScheduledTask -TaskName "Daily Backup" -Confirm:$false

# Export a task to XML
Export-ScheduledTask -TaskName "Daily Backup" | Out-File "C:\Backup\task.xml"

# Import a task from XML
Register-ScheduledTask -Xml (Get-Content "C:\Backup\task.xml" | Out-String) -TaskName "Daily Backup"

PowerShell Automation Scripts: Common, Backup & Maintenance

Now that we have a fundamental understanding of how to schedule and execute scripts both through the Windows Task Scheduler and PowerShell, it’s time to learn some specific and helpful scripts you can run automatically on your Windows server.

First, here is a script template you can reuse to customize your scripts:

<#
.SYNOPSIS
    Daily server backup script
.DESCRIPTION
    Backs up critical directories and databases to backup location
.NOTES
    Author: IT Team
    Date: 2025-01-01
    Version: 1.0
#>

param(
    [string]$BackupPath = "D:\Backups",
    [string]$LogPath = "C:\Logs\backup.log"
)

function Write-Log {
    param([string]$Message)
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    "$timestamp - $Message" | Out-File -FilePath $LogPath -Append
    Write-Host "$timestamp - $Message"
}

try {
    Write-Log "Backup started"
    
    $backupDate = Get-Date -Format "yyyyMMdd_HHmmss"
    $targetPath = Join-Path $BackupPath $backupDate
    New-Item -ItemType Directory -Path $targetPath -Force | Out-Null
    
    # Your backup logic here
    
    Write-Log "Backup completed successfully"
    
} catch {
    Write-Log "ERROR: $($_.Exception.Message)"
    exit 1
}

Common Automation Scripts:

Let’s go over some of the most common PowerShell tasks that can handle your everyday Windows server administrative tasks.

SQL Server Database Backup

For example, the script below is crafted to automatically back up all user databases on a SQL server instance, and then automatically removes old backups.

$serverInstance = "localhost"
$backupPath = "D:\SQLBackups"
$retention = 7 # days

Import-Module SQLPS -DisableNameChecking

$databases = Invoke-Sqlcmd -ServerInstance $serverInstance `
    -Query "SELECT name FROM sys.databases WHERE database_id > 4"

foreach ($db in $databases) {
    $dbName = $db.name
    $timestamp = Get-Date -Format "yyyyMMdd_HHmmss"
    $backupFile = "$backupPath\$dbName`_$timestamp.bak"
    
    Backup-SqlDatabase -ServerInstance $serverInstance `
        -Database $dbName -BackupFile $backupFile `
        -CompressionOption On
    
    Write-Host "Backed up $dbName to $backupFile"
}

Get-ChildItem $backupPath -Filter "*.bak" | 
    Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-$retention) } | 
    Remove-Item -Force

IIS Log Cleanup

This script, on the other hand, can easily remove old IIS log files based on the pre-defined retention period, which will keep your disk space available.

$iisLogPath = "C:\inetpub\logs\LogFiles"
$retention = 30 # days

Get-ChildItem $iisLogPath -Recurse -File | 
    Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-$retention) } | 
    Remove-Item -Force

Write-Host "Cleaned IIS logs older than $retention days"

Windows Update Check

This one is very helpful.

Using the following simple PowerShell script, you can check for available Microsoft updates, allowing IT professionals to complete patching management across servers. This is exceptionally helpful when you’re dealing with server clusters.

$updateSession = New-Object -ComObject Microsoft.Update.Session
$updateSearcher = $updateSession.CreateUpdateSearcher()

Write-Host "Searching for updates..."
$searchResult = $updateSearcher.Search("IsInstalled=0 and Type='Software'")

if ($searchResult.Updates.Count -eq 0) {
    Write-Host "No updates available"
} else {
    Write-Host "$($searchResult.Updates.Count) updates available:"
    $searchResult.Updates | Select-Object Title, IsDownloaded
}

Automating Windows Server Backups

The backup is an essential part of absolutely any Windows system maintenance approach, and using PowerShell scripts as a powerful tool, system administrators can easily schedule any kind of backup.

All of this, possible with a completely hands-off approach if you want to maintain the Windows OS.

File Backup

First, we’re going to review a script that uses PowerShell code to back up any important folders and also remove old backups. It’s probably the simplest and surface-level task automation example in the PowerShell environment.

$backupTarget = "D:\Backups"
$backupItems = @("C:\Data", "C:\inetpub\wwwroot", "C:\Users")

$timestamp = Get-Date -Format "yyyyMMdd"
$backupPath = Join-Path $backupTarget $timestamp
New-Item -ItemType Directory -Path $backupPath -Force

foreach ($item in $backupItems) {
    $itemName = Split-Path $item -Leaf
    $zipFile = "$backupPath\$itemName.zip"
    Compress-Archive -Path $item -DestinationPath $zipFile -CompressionLevel Optimal
    Write-Host "Backed up $item"
}

Get-ChildItem $backupTarget -Directory | 
    Where-Object { $_.CreationTime -lt (Get-Date).AddDays(-14) } | 
    Remove-Item -Recurse -Force

System State Backup

Here, we’re going to back up the Windows OS state by using a built-in PowerShell environment command. This is very important for restoring potentially lost system settings and user accounts in cases where something goes wrong with the system.

$backupLocation = "D:\SystemStateBackup"
$wbCommand = "wbadmin start systemstatebackup -backupTarget:$backupLocation -quiet"
Invoke-Expression $wbCommand

wbadmin get versions -backupTarget:$backupLocation

Scheduling Backup Tasks

If you want to schedule backup tasks, you’ll need to combine script development, manage script copies, and everything we’ve learned from automating tasks through the Task Scheduler.

Here’s what it looks like:

$action = New-ScheduledTaskAction -Execute "PowerShell.exe" `
    -Argument "-File C:\Scripts\Backup-Files.ps1"
$trigger = New-ScheduledTaskTrigger -Daily -At "2:00AM"
Register-ScheduledTask -TaskName "Daily File Backup" `
    -Action $action -Trigger $trigger -User "SYSTEM" -RunLevel Highest

$action = New-ScheduledTaskAction -Execute "PowerShell.exe" `
    -Argument "-File C:\Scripts\Backup-Database.ps1"
$trigger = New-ScheduledTaskTrigger -Daily -At "3:00AM"
Register-ScheduledTask -TaskName "Daily Database Backup" `
    -Action $action -Trigger $trigger -User "SYSTEM" -RunLevel Highest

See Also: How to Install and Remove Server Administrative (RSAT) Tools

Automating Windows Maintenance

The automation of maintenance on a Windows server is one of the most important deployments you can establish as soon as possible.

By using PowerShell cmdlets and PowerShell remoting, system administrators can easily monitor CPU usage, review logs, apply updates, and even generate reports without touching anything manually.

The scripts that we’re going to review work excellently with Power Platform & Power Apps, and can manage tasks such a creating new user accounts, password resets, and more.

Let’s go over some of the most essential scripts:

Windows Update Automation

The example script below automatically installs updates based on a specific schedule and even targets exact KB articles (when necessary).

Install-Module PSWindowsUpdate -Force

Get-WindowsUpdate

Install-WindowsUpdate -AcceptAll -AutoReboot

Get-WindowsUpdate -Install -KBArticleID "KB5000001"

$action = New-ScheduledTaskAction -Execute "PowerShell.exe" `
    -Argument "-Command Install-WindowsUpdate -AcceptAll -AutoReboot"
$trigger = New-ScheduledTaskTrigger -Weekly -DaysOfWeek Sunday -At "3:00AM"
Register-ScheduledTask -TaskName "Weekly Updates" `
    -Action $action -Trigger $trigger -User "SYSTEM" -RunLevel Highest

Event Log Cleanup for Disk Management

The example script below will check, detect, and delete potentially oversized logs while creating a backup for required auditing later. It can be extended to import a CSV file of retention policies, track GPU usage, and generate output for any remoting sessions.

$maxSize = 50MB
$logs = @("Application", "System", "Security")

foreach ($log in $logs) {
    $eventLog = Get-WmiObject Win32_NTEventlogFile | Where-Object {$_.LogfileName -eq $log}
    $currentSize = $eventLog.FileSize
    
    if ($currentSize -gt $maxSize) {
        wevtutil clear-log $log /backup:C:\Logs\$log-backup.evtx
        Write-Host "Cleared $log log (was $([math]::Round($currentSize/1MB,2))MB)"
    }
}

Service Monitoring and Auto-Restart

Another very powerful PowerShell script can monitor your essential services, such as SQL Server, IIS, and when something stops working, restart them and email an alert. It can also integrate with Graph API and Power Platform tools to track metrics such as new user accounts or even password resets.

$services = @("W3SVC", "MSSQLSERVER", "WinRM")

foreach ($service in $services) {
    $svc = Get-Service -Name $service -ErrorAction SilentlyContinue
    
    if ($svc.Status -ne "Running") {
        Start-Service -Name $service
        Write-Host "Restarted service: $service"
        
        Send-MailMessage -To "admin@example.com" `
            -From "server@example.com" `
            -Subject "Service Restarted: $service" `
            -Body "Service $service was not running and has been restarted" `
            -SmtpServer "smtp.example.com"
    }
}

Windows Script Automation with ServerMania

A CTA image listing the ServerMania advantages for Windows server automation.

Here at ServerMania, we’re ready to provide you with Windows Servers, built for complete automation, and offer system administrators complete access and control. Using popular scripting languages, we can help you streamline everything from automating updates, group memberships, and repetitive tasks to deploying modern modules, adopting command-line techniques, and managing system program files.

Our Windows Server environments are designed for full PowerShell automation, task automation, and seamless Windows maintenance, making it easier than ever for small businesses to automate workflows.

Explore: How Much Does a Windows Server Cost

The ServerMania Advantage:

✓ Pre-Configured Windows Server Environments
✓ Expert PowerShell and Automation Assistance
✓ 24/7 on-site Monitoring (Top-Tier Data Centers)
✓ 99.99% Uptime and Automatic Backup Solutions
✓ Availability of Both Windows & Linux OS Versions

Explore: ServerMania Colocation Services!

How to Get Started with Windows Automation:

  1. First, choose a service (Dedicated or Cloud Server)
  2. Then, select a Windows Server version (2019/2022)
  3. Deploy a Windows server with our expert assistance
  4. Start implementing essential automation techniques

💬If you have questions, book a free consultation or contact ServerMania’s support team and get started with your Windows server automation today. We’re available for discussion right now!