Run PowerShell Scripts as Windows Scheduled Tasks

It can be useful to have a PowerShell script which runs as a Windows Scheduled task to perform otherwise manual tasks. Being a lazy bugger I like to automate as many boring, shitty tasks as I can so PowerShell and Scheduled Tasks are my friends…

A good example of this would be if you needed to run a cleanup of WSUS to remove declined, superseded, expired updates etc.

The script I want to run looks like the following:

       Cleans up WSUS on local server
       PowerShell.exe -ExecutionPolicy ByPass -File WSUSCleanup.ps1
       Author:	Jonathan Conway
       Created:	21/07/2016
       Version:	1.1

# Set WSUS port number (standard is 8530 on Windows Server 2012 R2 but can be customised)
$WSUSPortNumber = 8530

# Connect to local server using PowerShell
Get-WsusServer -Name $env:computername -PortNumber $WSUSPortNumber

# Perform required cleanup commands
Get-WsusServer | Invoke-WsusServerCleanup -CleanupObsoleteUpdates -CleanupUnneededContentFiles -CompressUpdates -DeclineExpiredUpdates -DeclineSupersededUpdates | `
Out-File -FilePath C:\Tools\Scripts\wsuscleanup.log

In order to run this as a Scheduled Task in Windows I’d need to run it as SYSTEM (NT AUTHORITY\SYSTEM) – change the “Configure for:” section at the bottom to match the OS you’re using as well, for compatibility purposes.

Configure a Trigger – once a week should be more than enough for this particular task.

The action should be configured to “Start a Program” which would be as per the command line example below (example assumes you have a script called WSUSCleanup.ps1 located in a folder called “C:\Tools\Scripts”):

PowerShell.exe -ExecutionPolicy ByPass -File C:\Tools\Scripts\WSUSCleanup.ps1

It should end up looking a bit like this:


And that’s about it – should run as per the Trigger Schedule.

/ JC

This entry was posted in PowerShell. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s