TaskAgent & Windows PowerShell - Part 1

­During the Argos Software users’ conference in October 2008, I presented a session on how to extend the standard TaskAgent functionality using scripting with T-SQL and Windows PowerShell. In several blog posts I will try to make the examples and materials from that session available for all Argos customers. Check the “Downloads” section at the end of this post for the demo source files and other available downloads.

Prerequisites

You will need to install the latest version of the TaskAgent (available for download on our FTP server here: ftp://ftp.abecas.com) and Windows PowerShel version 1.0 (available for download here: http://www.microsoft.com/downloads/details.aspx?familyid=6CCB7E0D-8F1D-4B97-A397-47BCC8BA3806) in order to be able to use the examples below.

Scenario 1:  Automate file and directory maintenance

One common task which I have to do quite often involves maintenance of different files and directories. I wanted to configure a simple TaskAgent job which will monitor a specific file system directory every 15 minutes and will delete files which match certain criteria – in this specific case, delete all files which have been created more than 8 hours ago. Setting up in the TaskAgent a job schedule which triggers the job execution every 15 minutes is very easy. However, configuring a task to delete the necessary files is not straight forward. Initially I tried to do this with a simple batch file, but getting the current system date and time and using it to filter files proved to be quite difficult. After some research I found an easy answer which was using the newest scripting offering from Microsoft – Windows PowerShell, which is a standard part of Windows Server 2008 and is also available for Windows XP and Windows Server 2003. With PowerShell, all I needed to write is a single line of script code to achieve my task goal:

dir “D:\Temp” | ? {$_.CreationTime -lt (get-date).AddHours(-8)} | del –recur

This single line of code performs the following:

1.       Retrieves the list of all files and sub-direcotries in D:\Temp

2.       Iterates through the list and checks if the creation date & time of the file/sub-directory is more than 8 hours ago

3.       Each file/sub-directory, which matches the criteria above, is deleted and in the case of directories, all sub-directories and their content is deleted as well.

It is beyond the scope of this blog post to provide a full explanation and reference for using the Windows PowerShell – you can refer to the multitude of available online resources for that (one such reference can be found here: http://channel9.msdn.com/Wiki/WindowsPowerShellWiki/). However, I do want to show you how to integrate the PowerShell scripts in the TaskAgent to extend its functionality and automate a wide variety of tasks.

Here is what we need to do for our single-line script above:

1.       If you have not installed the Windows PowerShell on the TaskAgent server, do so.

2.       Open the PowerShell command prompt, enter the following command:

Set-ExecutionPolicy RemoteSigned

and press “Enter”.

PowerShell Console - Execution Policy

This command will enable the execution of PowerShell script files which are created on the TaskAgent server, because by default this option is disabled to prevent the execution of malicious scripts. (note: Windows PowerShell provides also options to enable only the execution of digitally signed scripts – you will need to have a certificate which can be used to sign your scripts). If you enter the command

Get-Help Set-ExecutionPolicy

You will get detailed description for the available options.

PowerShell Console - Execution Policy Help

3.       Create a simple text file using Notepad, copy and paste the script line above into your text file and save the file in a directory accessible by the TaskAgent using as filename demo_deletefiles_bycreationdatetime.ps1.

PowerShell script in Notepad

Note the extension .ps1 – by default, this is the extension used for PowerShell script files. If you are using Notepad to create the script files, when saving the files make sure that you specify in the “Save As Type” the option “All Files” – otherwise Notepad will append the default .TXT extension to your filename.

Save files in Notepad with extensions different than .TXT

You can use any text editor to create or modify the script files. The only requirement is to save the files as plain text ASCII or Unicode files. My favorite text editor is UltraEdit – it provides among other things color syntax highlighting for the PowerShell scripts which makes it easier to edit them. In the screenshot below, there is an extra line which starts with # - this designates a comment in your PowerShell script file. Such lines will be ignored during the script execution, they are used only to document your script code – very useful for the future script maintenance.

PowerShell script in UltraEdit

4.       Open the TaskAgent console and make sure the RunProgramWorker is registered and enabled – this is the worker which will be used to process the script tasks

TaskAgent workers configuration

5.       In the TaskAgent console, create a new job and add a date & time schedule for it – for this example I used a time schedule which is triggered every 15 minutes, every work day from 8am to 5pm – feel free to set the time schedule as you see fit. (note: to test the script task you do not even need a schedule – just a job with the necessary task, the job can be triggered manually using the option “Run Job Now”)

TaskAgent job and schedule

TaskAgent time schedule

6.       Add a task for the job created above – for the task type, select “Run External Program”

Adding in TaskAgent “Run External Program” task type

7.       On the “Task Settings” – “General” tab, in the “Program or File to Run” field, enter the PowerShell executable “powershell.exe” and in the “Command-line Parameters” field, enter the full path to the PowerShell script file.

Task settings - General tab

As a rule, I always surround the file paths with double-quotes to avoid errors if the file path contains spaces.

8.       On the “Task Settings” - “Security” tab, you can provide the Windows credentials which the TaskAgent should use when executing the external program (in our case this is the powershell.exe). By default, the TaskAgent will use the same credentials as the ones which the TaskAgent service is using.

Task settings - Security tab

9.       On the “Task Settings” – “Execution Result” tab, you can specify what the TaskAgent should do after the external program is successfully started. In this specific case, I have configured the task to wait for 20000 milliseconds (20 seconds) for powershell.exe to finish its execution. If the powershell.exe does not finish within the allocated period, the TaskAgent will terminate the external process. In addition, the TaskAgent can examine the exit code of the external process to determine whether the execution was successful or not. In this specific case, I have configured the task to accept only 0 as a successful exit code.

Task settings - Execution Result tab

This is all – now save the job and we are ready to test it! You can manually trigger the job by right-clicking on it in the TaskAgent console – Jobs list and selecting the option “Run Job Now”.

Online Resources

Below is the list of some of the available online resources which I have used.

•        Windows PowerShell

http://www.microsoft.com/windowsserver2003/technologies/management/powershell/default.mspx

http://www.microsoft.com/technet/scriptcenter/topics/winpsh/manual/start.mspx

http://channel9.msdn.com/wiki/windowspowershellquickstart/

•        Batch Files

http://commandwindows.com (Great One!)

•        SQL Scripts

http://msdn.microsoft.com/en-us/library/bb510741.aspx

The example above is a simple one. In the following posts I will  show more elaborate PowerShell scripts.

Downloads

A PDF version of the contents in this blog post is available for download here: TaskAgent & Windows PowerShell

A ZIP file containing the demo source files is available for download here: Sample PowerShell scripts and other source files from the demos

2 Responses to “TaskAgent & Windows PowerShell - Part 1”

  1. ABECAS Insight » Blog Archive » TaskAgent & Windows PowerShell - Part 2 Says:

    […] ABECAS Insight A weblog about configuring and running ABECAS Insight by Argos Software « TaskAgent & Windows PowerShell - Part 1 […]

  2. ABECAS Insight » Blog Archive » TaskAgent & Windows PowerShell - Part 3 Says:

    […] is Part 3 of the TaskAgent & PowerShell series. Here you can find Part 1 and Part 2 posts. Check the Downloads section at the end of the post for the available source files […]

Leave a Reply

You must be logged in to post a comment.