One of the things I've been working on for the past week was automating some
SVN (Subversion) administrative tasks. As I originally come from a Unix background my first thought was to use
PERL. In the past I've used PERL for lots of these kind of tasks on Windows Servers.
ActivePerl made it very easy to install on Windows boxes. Heck I even had a PERL script that FTPed into a remote server and downloaded files with a specific extension and deleted the files on the remote server after the download was over. That script ran for 3 years with minimum maintenance.
However I thought this time I'd see about using Microsoft PowerShell. I have to tell you I think PowerShell rocks. The best way I can describe PowerShell is it's the Windows equivalent of BASH or Korn shell in Unix or Linux. It allows you write a shell script for repetitive tasks, just like any other shell. In fact I found the syntax for PowerShell to almost be a blend of C# and PERL. So I felt comfortable writing PowerShell scripts very quickly.
In SVN I wanted to add new files to the repository. If you're using TortoiseSVN, this task is easy to do with the GUI. However I want files to be added to the repository any time a automated file sync happens. So I wrote a quick script for this:
$results = @(svn st)
$pattern = "^\?"
$re = new-object System.Text.RegularExpressions.Regex($pattern)
$resultCount = $results.length - 1
for($j=0; $j -le $resultCount; $j++)
{
$add = $results[$j]
$match = $re.Match($add);
if($match.Success)
{
$add = $add -replace("^\?.{6}","")
svn add $add
}
}
Let's go over what this script is doing. First we load the results of the "
svn st" command in an array.
$results = @(svn st)
Now we use a regular expression to find the items that need added. These are denoted by the "?" at the beginning of the line. So we define the pattern and set the System.Text.RegularExpression object. (This is the .NET System.Text.dll) Then we set the pattern "$re = new-object System.Text.RegularExpressions.Regex($pattern)".
Next we create a $resultCount variable that holds the number of items in our array. This will be used in our "for loop". Now we look through the items in the array, and if the item matches the regular expression it will be added to the SVN repository. However there's one hicup. The file path to be added from our array starts with "? ". So we need to trip that off. Again we use a simple regular expression and the -replace parameter, and now we have a correct path.
It's added to the SVN Repository and we're done. Well almost. We have to save the script into a ".ps1" file. However it won't run just yet. It has to be signed. Signing a PowerShell script isn't hard, but it does require some work. Scott Hanselman has a great post on his blog about Signing PowerShell Scripts that is just excellent, I highly suggest you read his tutorial.
Happy Coding