Sunday, January 27, 2008

Subversion post-commit email script via Powershell

I thought it'd be neat to keep tabs on all commits made to a certain Subversion repository I participate in, so I whipped up the following script in Powershell. Yeah, there are lots of post-commit scripts floating around, but they're primarily for non-Windows environments. Besides, it was easy and gave me an excuse to play with Powershell.

To use:
  1. Make sure you've installed Powershell (duh!).
  2. Copy the contents below to a file, say, c:\emailer.ps1
  3. Be sure to customize the $server, $to, and $from variables.
  4. Create a post-commit.bat file in your repository's "hooks" folder.
Put this in your post-commit.bat file:

%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe c:\emailer.ps1 "%1" "%2"

And here is the Powershell script itself:

# Sends an email message to the configured addresses, notifying
# of changes to the current repository
#

# customize the following
#

$server = "mail.server.ip.address.yourdomain.com"
$to = "youremailaddress@yourdomain.com"
$from = "fromemailaddress@yourdomain.com"

#
#

$REPOS = $args[0]
$REV = $args[1]
$name = $args[2]

if ($name -eq $null) { $name = $REPOS }

$author = svnlook author $REPOS --revision $REV
$subject = "SVN Commit: ($author) $name ($REV)"

$body = ""

foreach($log in svnlook log $REPOS --revision $REV) { if($log -ne "") { $body += $log + "`n" } }

if ($body -ne "") { $body += "`n`n" }

foreach($changed in svnlook changed $REPOS --revision $REV) { $body += $changed + "`n" }

$mailer = new-object Net.Mail.SMTPclient($server)
$msg = new-object Net.Mail.MailMessage($from,$to,$subject,$body)
$mailer.send($msg)

3 comments:

Anonymous said...

This was exactly what I was looking for. Have tried different ways of executing a PowerShell script but it is a bit difficult to debug so nice with a working sample.

Thanks.

Best regards
Anders

Anonymous said...
This comment has been removed by a blog administrator.
Chris Onec said...

I struggled over one hour to figure this out.

The Powershell script execution policy is different for 32bit process vs 64 bit process.

Since VisualSVN is a 32 bit [rpcess, to get this to work, you will need to set the ExecutionPolicy to Unrestricted FROM A *32 BIT* POWERSHELL prompt.