POWERSHELL   Powershell – Schedule a task on a list of servers remotely



Maybe you have been interested in configuring a scheduled task on a set of servers of your enviroment. Depending on the quantity it can become a tedious… or a reeeaaaaally tedious process (connect to every server, run "scheduled tasks" console, configure…)

So, as we, sysadmins, usually do… let's make the work easier using scripts…

In this example, the goal is configure a scheduled task on a set of servers to make them run a batch script (f.e. startup_script.bat) at 3am everyday. Using powershell this work will be done easily and quickly.

We'll need 3 components:

  • daily_script.bat – obviously, the example script that will do whatever we want that must exist before creating the scheuled tasks…
  • scheduled_task.ps1 – powershell script that creates a scheduled task on the local machine (to create tasks remotely you dont have to execute this one)
  • remote_scheduled_task.ps1 – powershell script that has to be execute to create a scheduled task on a set of remote machines which, in turn, uses "scheduled_task.ps1" script

I know this scripts can be much more versatile and efficient. The trigger is not configurable (you have to change code) and is ready only for execution everyday at 3am. Maybe instead of variables, parameters or a configuration file, error management, etc… but this is what i needed at certain moment and I share them supposing it can be helpful for you after modifying them for your needings…

Scheduled_task.ps1

Creates a scheduled task at 3am daily with the highest privileges of the configured credentials.

This is the code you can download here:

####################### CONFIG ##########################
# Credentials to be configured in the scheduled task
$USER = "domain\user"
$PASS ="pass*word"

# Scheduled task name
$TASKNAME = "Daily Script"

# Scheduled task folder
$TASKPATH = "MyTASKS"

# Scheduled task description
$DESCRIPTION = "This is my task description"

# Script to schedule
$SCRIPT="C:\SCRIPTS\startup_script.bat"
########################################################

Function CreateScheduledTaskFolder ($TASKPATH)
{
    $ERRORACTIONPREFERENCE = "stop"
    $SCHEDULE_OBJECT = New-Object -ComObject schedule.service
    $SCHEDULE_OBJECT.connect()
    $ROOT = $SCHEDULE_OBJECT.GetFolder("\")
    Try {$null = $SCHEDULE_OBJECT.GetFolder($TASKPATH)}
    Catch { $null = $ROOT.CreateFolder($TASKPATH) }
    Finally { $ERRORACTIONPREFERENCE = "continue" } 
}


Function CreateScheduledTask ($TASKNAME, $TASKPATH)
{
    $ACTION = New-ScheduledTaskAction -Execute "$SCRIPT"
    $TRIGGER =  New-ScheduledTaskTrigger -Daily -At 3am
    Register-ScheduledTask -Action $ACTION -Trigger $TRIGGER -TaskName $TASKNAME -Description "$DESCRIPTION" -TaskPath $TASKPATH -RunLevel Highest
}

Function ConfigureScheduledTaskSettings ($TASKNAME, $TASKPATH)
{
    $SETTINGS = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -Hidden -ExecutionTimeLimit (New-TimeSpan -Minutes 5) -RestartCount 3
    Set-ScheduledTask -TaskName $TASKNAME -Settings $SETTINGS -TaskPath $TASKPATH 
}

CreateScheduledTaskFolder $TASKNAME $TASKPATH
CreateScheduledTask $TASKNAME $TASKPATH | Out-Null
ConfigureScheduledTaskSettings $TASKNAME $TASKPATH | Out-Null

$PASSWORD = ConvertTo-SecureString "$PASS" -AsPlainText -Force
$CREDENTIALS = New-Object -typename System.Management.Automation.PSCredential -argumentlist $USER, $PASSWORD
 
Set-ScheduledTask -TaskName "$TASKNAME" -TaskPath "$TASKPATH" -User "$USER" -Password "$PASS" | Out-Null

This should be the result if launching this script (to create tasks remotely you dont have to execute this one):
Powershell - Schedule a task on a list of servers remotely
powershell-schedule-a-task-on-a-list-of-servers-remotely-2

I havent parametrized things like the trigger or other settings. You can change this lines…
In the CreateScheduledTask function to change trigger properties:

$TRIGGER = New-ScheduledTaskTrigger -Daily -At 3am

In the ConfigureScheduledTaskSettings function to change some settings:

$SETTINGS = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -Hidden -ExecutionTimeLimit (New-TimeSpan -Minutes 5) -RestartCount 3

Refer to the documentation to see the available options:
New-ScheduledTaskTrigger https://technet.microsoft.com/library/jj649821%28l=wps.620%29.aspx
New-ScheduledTaskSettings https://technet.microsoft.com/library/jj649824%28v=wps.630%29.aspx

Remote-Scheduled_Task.ps1

Given a list of servers, for each of them remotely copies the script (in this case daily_script.bat) to it (same path) and creates the scheduled task.

This is the code you can download here:

######################## CONFIG ########################
# File containing the list of servers
$SERVERS_FILE="servers.txt"

# Script that will be copied to the remote server
$SCRIPT="C:\SCRIPTS\daily_script.bat"
########################################################

$REMOTE_FILE=$SCRIPT -replace ":","$"
$SERVERS=Get-Content $SERVERS_FILE

Foreach ($SERVER in $SERVERS)
{
	If(Test-WSMan -ComputerName $SERVER -EA 0)
	{
        "Configuring the task on server $SERVER..."
        Copy-Item -Path "$SCRIPT" -Destination "\\$SERVER\$REMOTE_FILE"
		Invoke-Command -ComputerName $SERVER -FilePath ".\SCHEDULED_TASK.ps1"
	}
	Else 
	{
		"$SERVER is not available"
	}
}

After preparing a file containing a list of servers…
Powershell - Schedule a task on a list of servers remotely

…you can create the scheduled tasks on each of them…

PS D:\SCRIPTS\SCHEDULED_TASK> .\REMOTE_SCHEDULED_TASK.ps1
Configuring the task on server SERVER01...
Configuring the task on server SERVER02...
Configuring the task on server SERVER03...

PS D:\SCRIPTS\SCHEDULED_TASK>

2 thoughts on “Powershell – Schedule a task on a list of servers remotely

  1. Hi,
    Can I do this for a “run on demand” script?
    Basically I need to run an exe on demand to update an application on several remote PCs. What I was thinking what create a task on each remote PCs with a PS script. This task would then run a PS script that would execute the exe file.
    But I need to run this on demand and not scheduled. How do I go about this this?
    Thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *