Skip to content

CategoryAutomation / Scripting

Send A File Path from the Windows Context Menu to App

Here’s an easy way to pass the file path to a console app. I needed a way to right click on a folder or a file, and send the path to a console app, where the app does its thing with the file(s).

To show you what I mean:

When I right-click on “coolbeans” it runs the following console app, which simply displays the path:

The C# app is pretty straightforward. Basically, once you have the file path, you can apply any operations on the file.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace dan_rocks
  class Program
    static void Main(string[] args)

So there’s nothing crazy going on in the above sample. You basically just have to add a few entries to the Registry.

If you want to pass a folder path when you right-click on it, and select the option in the context menu, create a new entry:


If you want to pass in a file, do the following:


Let’s pass in the filepath to note.exe:

Do that and you’ll see the following:

Compress and Move Log Files

Sometimes log files bog a system down. For one of our servers, I made this little Python script that compresses (via WinRAR) the log files in a directory, and then moves them to a backup location. The only little catch is that I wanted to leave the latest log files for in that directory. Log files are created daily, so the the latest log files have a datestamp of today. Here’s how I did it.

First Create the Python Script:

import os
import datetime

dateStamp  ="%Y-%m-%d") 
imsLogPath = 'd:\\LogFiles\\'                     
# Don't use a mapped drive but use UNC for network drives. Task Schedule seems to choke when it calls Python.
newRARPath = '"\\\\\\Root\\backups\\' + dateStamp + '.rar"'
rarPath    = '"C:\\Program Files\\WinRAR\\rar.exe" a -m5 ' + newRARPath 

# Get Latest Files
smtpLatest   = os.popen(r"dir /od /a-d /b " + imsLogPath + "SMTP*.log").read().splitlines()[-1]
postLatest   = os.popen(r"dir /od /a-d /b " + imsLogPath + "POST*.log").read().splitlines()[-1]
ischedLatest = os.popen(r"dir /od /a-d /b " + imsLogPath + "iSched*.log").read().splitlines()[-1]
relayLatest  = os.popen(r"dir /od /a-d /b " + imsLogPath + "Relay*.log").read().splitlines()[-1]
qengLatest   = os.popen(r"dir /od /a-d /b " + imsLogPath + "Qeng*.log").read().splitlines()[-1]

# Get List of All Files
allFiles     = os.popen(r"dir /od /a-d /b " + imsLogPath + "*.log").read().splitlines()

# Remove Latest Files from All Files List
allFiles.remove( smtpLatest )
allFiles.remove( postLatest )
allFiles.remove( ischedLatest )
allFiles.remove( relayLatest )
allFiles.remove( qengLatest )

# allFiles Array Has the list of files

# Flatten Array allFiles to be used as a parameter in system command
flatLogPathList = ""
for filenameWithPath in allFiles:
  flatLogPathList = flatLogPathList + imsLogPath + filenameWithPath + " "

# Execute WinRar
path = rarPath + " " + flatLogPathList.rstrip()
os.system( '"' + path + '"' )

# Delete all log files
os.system( '"del ' + flatLogPathList.rstrip() + '"' )

Then I set up the Scheduled Task:

With these Settings:

Get Latest File

In my last post, I made a quick script that checks for the date. It was very limiting, since it used the dir command. This one uses several date/time Python modules and is more capable.

import os, os.path, stat, time
from datetime import date, timedelta, datetime

# Reference

def getFileDate( filenamePath ):    
  used = os.stat( filenamePath ).st_mtime      
  year, day, month, hour, minute, second = time.localtime(used)[:6]
  objDateTime = datetime(year, day, month, hour, minute, second)
  return objDateTime
  # Ways to reference this DateTime Object
  # objDateTime.strftime("%Y-%m-%d %I:%M %p")
  # objDateTime.year
  # objDateTime.month

def isDaysOldFromNow( filenamepath, days ):
  # Checks how old a file is. Is it older than "days" [variable] days?
  inTimeRange = False  
  timeDeltaDiff = ( filenamepath ) ).days
  # Check if the file's date is days old or less:
  if ( timeDeltaDiff >= days ):
    inTimeRange = True  
  return inTimeRange

fname = "C:/temp/decision2.pdf"  

# Set this variable to check if the file is this days old
howOld = 3

if ( isDaysOldFromNow( fname, howOld ) ):
  print fname, "is more than", howOld, "days old"
  print fname, "is NOT more than", howOld, "days old"


Console2 Alternative to CMD

You know what, I tried PowerShell and I guess I never got used to it. I’ve been using DOS for the longest time that I prefer its simplicity when navigating through files. As far as scripting with it – forget it – it’s very cryptic and limiting, not to mention awkward. That’s why for scripting now I’m using Python. Nonetheless though, I sometimes need a playing field to run the scripts for, or running console utilities. That’s where Console2 comes in.

Console2 is a great tool that provides tabbing (you can tab through multiple consoles) and several ways to customize the UI. Here’s an example:

I prefer this configuration:

How I Have It Setup

Download Console2:

I have the Console2 open up when I hit CTR+\ via AutoHotkey. Here’s the snippet for this to happen in AutoHotkey. I have this run when Window starts (it must stay in memory).

^\::Run C:\dan-local\dos-win\Console.exe

Change the CMD prompt by creating a PROMPT system variable:

Download the Console2 Config File

Other Tips

Good tip about command console = CTRL+I
can select files in the current directory, kinda like autofill-in
you can also put in parts of the file and it autoputs it for you

Rename tab

New Tab with default transparency

New Tab with lighter transparency

Switch to NEXT adjacent tab

Switch to Previous adjacent tab

Goes to the tab instance. To make it easier, it’s best if you rename your tabs,


So for example,

1.Batch File
2.wget list
3.ftp the files

Using Winrar from the Command Line

Winrar is a great tool used for compressing files. It also has a command line tool called “rar.exe” to compress files, in case you want to batch it up. Here’s an example of the most common switches I use.

"C:\Program Files\WinRAR\rar.exe" a -m5 -r -ep1 "C:\temp\Work\Upgrades\2010-02-06\111.rar" "C:\temp\Work\Upgrades\2010-02-06\Post-Upgrade\" 

First path is the location of the rar file to create. The second path is either the location of the file(s) or directory to compress.

options used

  -ep1  Exclude base directory from names
  a     Add files to archive
  -r    Recurse subdirectories (will compress entire directories)
  -m5   Set compression level to maximum

You can even assign a password to it using the -p switch

Fast Delete

I needed to delete 30,000 files that took about 60 GB. I know traditionally it takes forever to delete it in Windows. Even using the “del” command in the console, it’s always been slow for me. Enter Robocopy. I never gave it a chance until today. The way it can delete is by syncing directory against an empty one which was just what I needed. It was able to do it in about 50 seconds. Awesome.

You’ll have to download Robocopy as part of the Windows Server 2003 Resource Kit Tools.

What I used to delete this big directory:

robocopy /MIR c:\empty-directory c:\my-files-to-delete

Testing Database Import Scripts with Snapshots

Can’t stress enough how handy database snapshots (compatible only in Enterprise and Developer editions of SQL Server 2005+) come in when testing bulk imports, data scrubbing, or any sort of data / schema modification script. In nearly no time, I can create a snapshot (via shortcut snippet), run my script – don’t like the results? My script crapped out the data? I can run an instant undo by recovering from the snapshot, which works pretty fast. If I want to create another snapshot, I usually tend to overwrite the snapshot I created, and then create it again.

It’s so handy that I have a snippet for it:

Anywhoot, here’s how you create a snapshot:

CREATE DATABASE YourDatabase_snap ON         -- Name of new snapshot
  NAME = yourdb_data,                        -- Logical filename of source db you want to snapshot
  FILENAME = 'c:\'  -- Sparse file to create
AS SNAPSHOT OF YourDatabase;                 -- Source db name
USE master;
RESTORE DATABASE YourDatabase                    -- Source db name where the data resided
FROM DATABASE_SNAPSHOT = 'YourDatabase_snap';    -- Snapshot db name

Deleting a snapshot is just like dropping a database.

DROP DATABASE YourDatabase_Snap

Computer Tools for the Power User

Here’s a list several tools I use both at home and work. I usually carry these on my USB keychain for easy access. They’re mostly lightweight, fast, and some don’t even require a installation. These are free and NOT Shareware! They are for Windows/Windows XP.


Used for file comparisons. You can compare text files and see, line by line where these files are different.

Great editor for HTML. This integrates nicely into Internet Explorer to “view source.” It can collapse HTML tags.

Microsoft Notepad on steroids. It uses color coding for files of various extensions. Uses transparency so that you can see through the editor window what’s behind it.

Agent Ransack
Search for text in files. The results show you the file and what line your keyword search is in.

Password Manager
It saves your passwords. You can create categories for what kind of passwords they are. Once you save it, you hit CTRL+U to save the user name, and CTRL+C to save the password to the clipboard. It uses a secure 448 bit Blowfish algorithm to ensure the data are not crackable. The password used for securing access to stored data is not saved anywhere.

JR Screen Ruler
A visual ruler you can use to measure pixels on the screen.

Record whatever you do at your Windows Desktop, and can replay them exactly. This is great to record tasks and save them for later.

Get a checksum for a file using hashes: crc16, crc32, xsum, md5.

Telnet/SSH Client

Process Explorer
See information about processes: what files or directories they have open. Kill processes, etc.

Know exactly what’s running when you start windows and turn those annoying programs off.

Simple File Schredder
Simple File Shredder is a utility that securely deletes your files so they can’t be restored.

Restore Deleted Files
This restores files that have been deleted. Use this as a last line of defense. The great thing about this program is that it does not require to install – unlike other applications, where you need to install first.

Angry IP Scanner
Angry IP scanner is a very fast IP scanner and port scanner. It can scan IP addresses in any range as well as any their ports. Its binary file size is very small compared to other IP or port scanners.

Change the date stamp for any file you want.

Great popup blocker.

Good firewall software.

System Spec
System Information Utility. Get a report for practically everything you wanted to know about your computer.

Synchronize files from different folders. I use this to synchronize files from my computer and USB keychain and USB drive. Lots of features.

Microsoft PowerToys for Windows XP
PowerToys add fun and functionality to the Windows experience. What are they? PowerToys are additional programs that developers work on after a product has been released. These tools include: Synchronize file tool, Image resizer to resize a batch of files, power calculator, multiple desktops, tweak UI settings, and more productivity tools.

Windows Internet Browser Plugins

Web Developer Plugin for Firefox
Provides a variety of tools for quickly creating, understanding, and troubleshooting Web pages. This feature is added to the menu when you right click on a page.

Internet Explorer Developer Toolbar
Provides a variety of tools for quickly creating, understanding, and troubleshooting Web pages. This feature is added to the menu when you right click on a page.

IE Context Menu Toolset
This is a set of tools which extend the right-click context menu of Internet Explorer. By simply installing these tools, your browser will have added functionality which can greatly help in debugging pages, designing sites, diagnosing form problems, tweaking design, etc.

Fiddler is a HTTP Debugging Proxy which logs all HTTP traffic between your computer and the Internet. Fiddler allows you to inspect all HTTP Traffic, set breakpoints, and “fiddle” with incoming or outgoing data. Fiddler is designed to be much simpler than using NetMon or Achilles, and includes a simple but powerful JScript.NET event-based scripting subsystem.

Command Console Tools

Like the dir command but displays files/directories with color and in columns.
Way much better! The drawback is if your OS is not using FAT12 or FAT16 type disks, the Bytes Consumed will be wrong.

Great Hexeditor. The only Hexeditor I use.

Get md5 hashes of files or text you type in. Useful if you need to find the md5 hash of a word.

Other Great Sites for Small Tools

These two sites have great little apps for networks, programming, graphics, etc. These are also free.

Systinternals Freeware

Setting Up Ant


Ant (Another Neat Tool) is a tool to automate tasks needed to run successful builds, deployments, and tests. You can run Ant as a stand-alone tool, or run it from Eclipse.

Needed JAR Files

In Ant, a "task" is a single line of instruction that gets run in the build file, as opposed to a "target" which is a group of tasks. There are a core set of tasks in Ant: copy, delete, echo, and many more ( Other important tasks (like FTP/SVN/Mail functionality), however, are not included. For that reason, we need to include these "add-ons" into Ant in the form of JAR files into Ant’s classpath.

The following is a list of additional tasks we need, that are not part of Ant’s core task list (download these before reading on):

Setup to Run Stand-Alone

  1. Install the JRE, if you don’t already have it.
  2. Download latest version of ANT: and unzip to c:\Ant
  3. Download the above latest JAR Files in Zip files. Zip files you download may have more than just JAR files, but you need to isolate these JAR files and put the JAR files into Ant’s classpath, C:\Ant\lib

  4. Put all the JAR files under C:\Ant\lib
  5. Add the following variables to your SYSTEM Variables

    Add this to your existing PATH variable:


    Also, make sure there’s a CLASSPATH and JAVA_HOME system variables setup for the JRE.

    CLASSPATH=.;C:\Program Files\Java\jre1.6.0_07\lib\ext\  
    JAVA_HOME=C:\Program Files\Java\jdk1.6.0_07  

  1. That should be it. Try to run, go to the command console and type "ant". To load a build file, type:
    ant \-buildfile build.ant  

Setup to Run From Eclipse

The typical Eclipse setup already comes with the core Ant tasks, so you just have to get the optional ones. Download the attachment and preferably put them here: C:\Ant\lib

  1. Run Eclipse
  2. Go to Run > External Tools > External Tools Configurations
  3. Double click on the Ant Build Icon
    This will open up the "New_Configuration Wizard"

  4. Name the build DeployStaging (there should already be a name in the field, but it’s called "New_configuration"
  5. Under the Main tab, put in the Buildfile (in this case, "Browse File System…") – browse to where your buildfile is. (No need to include the .properties file, as the build file will call it.)
  6. Under the Classpath tab, click on User Entries then click on "Add External JARs…" and point it to the directory which has all the JARs you downloaded (C:\Ant\lib).
  7. Select all the JARs.
  8. Click Apply.
  9. Click Close.
  10. Save if prompted.
  11. Select the build file and then Go to Run > Run
  12. To Modify the script you’ve just setup, go to Run > External Tools > External Tools Configurations
  13. To select another default target (for example, for to get the latest changes), go to the Targets tab, uncheck the default, and select the target you want (in this case, "update_latest").
  14. Click Apply and close.
  15. To see the build progress in detail, open up the console view by Window > Show View >Other > General > Console.

LogParser to Query IIS logs using SQL

LogParser is a great way to query IIS logs (any text log, actually, that is delimited).

Once you have it installed (default install is to C:\Program Files\Log Parser 2.2), let’s try to query log file ex090915.log from directory C:\WINDOWS\system32\LogFiles\W3SVC1942853941 . The way you would do this, is this:

LogParser "select date, s-ip, cs-method from C:\WINDOWS\system32\LogFiles\W3SVC1942853941\ex090915.log" -rtp:-1

As you can probably imagine, “date”, “s-ip”, and “cs-method” are the column headers from the log file. The select statement goes in quotes. Also, rather naming a table, you give the path to the log file. What’s the argument -rtp:-1 ? If you don’t include this argument, every 10 results, it will prompt you to “press a key…,” then will show you the next batch of results. In any case, the select state we just ran will spit out the following in the console:

date       s-ip            cs-method 
---------- --------------- ---------
2009-09-15 GET
2009-09-15 GET
2009-09-15 GET
2009-09-15 GET
2009-09-15 GET
2009-09-15 GET
2009-09-15 POST
2009-09-15 POST

Elements processed: 27
Elements output:    27
Execution time:     0.02 seconds

LogParser will even generate graphs (.gif format) of your results.

If you want to use a GUI for your queries, I suggest you try Log Parser Lizard.

Executable Extension

Want to run a script in the command console that is not of type EXE, COM, BAT by just typing in the name of the script? Have a script in Perl or Python that you have that you want to run without typing the name of the interpreter with switches? It’s pretty easy to do in Windows.

  1. Open up System Properties and click on Environment Variables:

  2. Select the PATHEXT System variable and click on the Edit button.

  3. Add the extension you want. In this case, let’s add the extension for .PL so we can run Perl scripts without typing in the name of the Perl interpreter:

  4. Hit OK on the Windows.
  5. In an Explorer Window, Go to Tools -> Folders

  6. In the Folder Options Window, click on the File Types tab, and then click New:

  7. Type .PL for the File Extension

  8. Click OK then Click on the Advanced button to open up the Edit File Type and click on New…

  9. Enter the name of the interpreter:

  10. Hit OK for all Windows.
  11. You’re set and good to go.

Now let’s test it. Make a .pl file under c:\ called "". Make be:

$sum = $ARGV[0] + $ARGV[1];
print "\nSum of the numbers is: $sum\n\n";


Now let’s call it via the console by typing:

add 5 5


ANT Script to Deploy

A friend of mine asked me to post a simple script to show the power of ANT. Here it is with comments that show some of the things you can do with it. To read how to set up ANT and run scripts, please read my earlier post on doing so.

This script gets the latest from an SVN repo, deploys using FTP, then sends an email using a Gmail account. Here’s the ant script (deploy.ant), followed by a properties file (i.e. the config file,, which the ANT script pulls from:

<?xml version="1.0"?>
<!-- ======================================================== -->
<!-- Sample build file used to retrieve svnant's sources -->
<!-- ======================================================== -->

<!-- TODO: Mail if the script failed --> 
<project name="STAGING-Deploy" basedir="." default="empty">
  <property file="" />            
  <!-- Import SVNAnt tasks from jar files.  -->
  <typedef resource="org/tigris/subversion/svnant/svnantlib.xml" />
  <target name="Deploy"> 
    <!-- Step 1: Export the latest files from the repo to local machine. -->
    <antcall target="export" />
    <!-- Step 2: FTP the files from the local machine to STAGING. -->
    <antcall target="ftp_files" />
    <!-- Step 3: Cleanup. -->
    <antcall target="cleanup" />  
  <!-- SVN Checkout (Latest) -->
  <target name="checkout_latest">
    <svn username="${svnant.repository.user}" password="${svnant.repository.passwd}">
      <checkout url="${svnant.projectrunk.url}" revision="${svnant.checkout.revision}" destPath="${svnant.checkout.destpath}" />
  <!-- SVN Update -->
  <target name="update_latest">
    <svn username="${svnant.repository.user}" password="${svnant.repository.passwd}">
      <update dir="${}" recurse="${svnant.update.recurse}" revision="${svnant.update.revision}" />
  <!-- SVN Export  -->
  <target name="export">
    <svn username="${svnant.repository.user}" password="${svnant.repository.passwd}">
      <export srcUrl="${svnant.export.srcurl}" destPath="${svnant.export.destpath}" force="${svnant.export.force}" />
  <!-- FTP the export of the latest revision to STAGING. -->  
  <target name="ftp_files">    
    <!-- Import FTP tasks from jar files.  -->
    <taskdef classname="" name="ftp" />
    <ftp server="${ftp.server}" port="${ftp.port}" remotedir="${ftp.destination}" userid="${ftp.userid}" password="${ftp.password}" 
         passive="${ftp.passive}" depends="${ftp.depends}" binary="${ftp.binary}" retriesAllowed="${ftp.retriesallowed}" verbose="${ftp.verbose}">
      <fileset dir="${svnant.export.destpath}" />
  <!-- Cleans Up: Remove temp info, etc. -->
  <target name="cleanup">  
    <delete includeEmptyDirs="true">
      <fileset dir="${svnant.export.destpath}"/>      
    <!-- Email Notification -->
    <mail mailhost="${}" mailport="${mail.port}" subject="${mail.subjectalert}" ssl="${mail.ssl}" user="${mail.username}" password="${mail.password}">
      <from address="${mail.from}"/>      
      <to address="${}"/>
      <message>The nightly build has completed.</message>
    <echo>Cleanup complete. </echo>
  <target name="empty">    
    <echo>Pass in a default target to call </echo>    


Now let’s check out the properties file (

# -----------------------------------------------------------------------------
# Variables are initialized here.
# -----------------------------------------------------------------------------
# NOTE: Backslashes have to be escaped with another backslash (on Windows)

# === INIT =====================================================================

# === CHECKOUT (INITIAL) =======================================================
# Check out a working copy of the latest to a local directory.

# === UPDATE TO LATEST =========================================================
# Update the working copy of your local directory to latest revision\\Experiments\\Firehawk\\src_latest

# === EXPORT ===================================================================
# Copies From Source Repo:

# Into a temporary directory in your ant home (that will be FTP'd):

# Overwrite (needs to in case the file changed)? 

# == FTP INFO ==================================================================
# FTP what was exported (latest version) to this location on staging:

# == MAIL INFO ==================================================================
# Currently using GMAIL for now.
mail.subjectalert=[STAGING ANT Build] Test build

Automate FTP Uploads

I thought this might be useful for those who are constantly uploading the same files. Whether you need to deploy a project live or constantly upload the same group of files, you can do this by creating a batch file in Windows using ftp.exe.

First of all, if you’re not familiar with FTP.exe, it’s just a command console way to upload/download files from an FTP server. You can run this program and start typing away…. OR, you can load a text file filled with FTP commands in FTP.exe. For example, the following are commands in a file called

send index.htm
send frame.htm
send car.jpg

The above should be straightforward. The “open” command is used to connect to the FTP server. The “username” should be your usename and “password” should be your actual password. “binary” is how your data should be handled on transfer – if it’s not text, it’s binary data, and should be “binary.” “hash” makes the console display pound signs (#) to serve as a progress bar as it’s uploading to the server. The “send” commands are used to upload the files. “bye” is exits the FTP session.

That was just a FTP script session file. You now need to call that file from FTP.exe on WindowsXP. You do that as follows:


You can include that call in a file called “upload.bat” – To learn more about FTP scripting and how to merge the two files into just one batch file, you can check out this site. Also, there’s more information about this found here:

Run Program, Resize it, Relocate it

My work often changes. I could be doing programming, then systems administration, then quality assurance. I often have to change from different toolset to toolset and I find it annoying sometimes having to rerun programs and moving them to the same locations. Then resizing. Eech. This is especially frustrating when I’m doing testing and I have to debug and read requirements all at the same time. One handy thing to do is to use AutoHotkey, the great scripting tool.

Here’s a handy script I put together that opens up two different programs, moves them on the screen and resizes the Window. Just copy and paste the same block of code for each program to open as may apps as you want with whatever on-screen configuration you want.

; Run Note.exe
; WinMove, WindowTitle, WindowText, X-Axis, Y-Axis, [, Width, Height]
Run, note.exe
WinWait, Untitled - Notepad2
WinGetPos,,, Width, Height, Untitled - Notepad2
WinMove, Untitled - Notepad2,, 500, 500, 200, 200

; Run your browser with the following URL
WinWait, tigers - Google Search - Mozilla Firefox
WinGetPos,,, Width, Height, tigers - Google Search - Mozilla Firefox
WinMove, tigers - Google Search - Mozilla Firefox,, 900, 200, 300, 400

Handling Images from the Command Line

Recently, I needed to do some work from the Windows Command Line, and I needed to deal with a few images. Along the way, I found some great tools. All these tools are free. Can come in useful when automating.


ImageMagick – This is a collection of command line tools. You can do image conversion, view properties, transform, transparency, join, overlay, add special special effects, and tons more. Also has APIs for C, C++, Java, .NET, Perl, PHP, Python, Ruby, and others. Highly recommend it.

Screen Capture

CmdCapture – Takes a screenshot of your desktop from the command line.

IECapt – Capture Internet Explorer’s rendering of a web page into a BMP, JPEG or PNG image file.

Cutycapt – Capture WebKit’s rendering of a web page into a variety of vector and bitmap formats, including SVG, PDF, PS, PNG, JPEG, TIFF, GIF, and BMP.

wkhtmltopdf – Convert HTML to PDF using the Webkit rendering engine, and Qt.