Tag: Script

Powershell script to create a new scheduled task with arguments and settings

While working on a SQL migration from Rackspace to Azure, we needed a solution to copy over transaction logs that were created every 1, 5, and 15 minutes depending on the database. These logs had a rolling window of 72 hours, meaning that every time a new file was written, the file that was older than 72 hours was deleted. We decided to use a simple robocopy script with the /MIR option to do the job as it was quick and easy. The hard part (okay, not “hard”, but “labor intensive” – and we don’t like that) was creating a lot of scheduled tasks to do the job.

If you have to do it more than once – write a script for it. Right?

This is not the script we used to copy the files up to Azure Blob Storage (I may write a blog post about that later), but here’s a sample script that the scheduled task will run to get you started: robocopy.ps1

Param
(
 [Parameter(Mandatory=$true,
 Position=0,
 HelpMessage="Source folder")]
 [string]$source,
 [Parameter(Mandatory=$false,
 Position=1,
 HelpMessage="Destination folder")]
 [string]$destination
)

robocopy $source $destination /MIR 

As you can see, the robocopy.ps1 accepts 2 parameters: $source and $destination. Because of the /MIR option, this small script will simply mirror the contents of the source directory into the destination – meaning that it will delete things in the destination folder as well if they are deleted in the source folder, so keep that in mind. We pass these parameters in when setting up our scheduled task.

Here is the script that creates the scheduled task with user input for parameters:


<#
.SYNOPSIS
    This script creates a scheduled task which calls another powershell script to perform a basic robocopy at a user selected interval indefinitely.

.DESCRIPTION
    The scheduled task calls robocopy.ps1, which copies the contents of 1 directory to another with the /MIR switch

.PARAMETER TaskName
    The name of the task to be created.

.PARAMETER Source
    Source folder to be replicated by the script.

.PARAMETER Destination
    Destination folder for items to be copied to.

.PARAMETER Interval
    Time, in minutes, between runs.

.EXAMPLE
    New-RepeatingScheduledTask -TaskName test -Source c:\1 -Destination c:\2 -Interval 1
#>


function New-RepeatingScheduledTask
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$true,
            Position=0,
            HelpMessage="The name of the task to be created.")]
        [string]$TaskName,
        [Parameter(Mandatory=$true,
            Position=1,
            HelpMessage="Source folder to be replicated by the script.")]
        [string]$source,
        [Parameter(Mandatory=$true,
            Position=2,
            HelpMessage="Destination folder for items to be copied to.")]
        [string]$destination,
        [Parameter(Mandatory=$true,
            Position=3,
            HelpMessage="Interval (in minutes)")]
        [string]$interval
    )
    
    Begin
    {
        $user = "NT AUTHORITY\SYSTEM"

        $TaskAction = New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument "-command `"& c:\users\chris.lee\documents\robocopy.ps1 -source $source -destination $destination`""
       
        $Interval = New-TimeSpan -Minutes $interval

        $startTime = (get-date).AddMinutes(1).ToString("HH:mmtt")

        $TaskTrigger = New-ScheduledTaskTrigger -Once -At "$startTime" -RepetitionInterval $Interval -RepetitionDuration ([TimeSpan]::MaxValue)
    }
    
    Process
    {
        Register-ScheduledTask –TaskName “$TaskName” -Action $TaskAction –Trigger $TaskTrigger -User $user

        Start-ScheduledTask -TaskName "$TaskName"
    }
    
    End
    {
        Get-ChildItem $destination
    }

}

New-RepeatingScheduledTask

Simply call your script and pass in the parameters when prompted, like so:

PS C:\Windows\system32> C:\Users\chris.lee\Documents\New-RepeatingScheduledTask.ps1
cmdlet New-RepeatingScheduledTask at command pipeline position 1
Supply values for the following parameters:
(Type !? for Help.)
TaskName: test
source: c:\1
destination: c:\2
interval: 1

TaskPath                                       TaskName                          State     
--------                                       --------                          -----     
\                                              test                              Ready     

LastWriteTime : 5/7/2016 8:51:34 PM
Length        : 18558
Name          : zero.jpg

PS C:\Windows\system32> 

After interval, you can see the TaskName displayed and the contents of the destination folder displayed.

You can also verify that your scheduled task was created by open Task Scheduler, or typing Get-ScheduledTask -TaskName (the name you defined) in your Powershell window.

PS C:\Windows\system32> Get-ScheduledTask -TaskName test

TaskPath                                       TaskName                          State     
--------                                       --------                          -----     
\                                              test                              Ready     

>

Any updates to the script will be made in my github repo: https://github.com/cd83/powershell

Facebooktwitterredditpinterestmail