Wednesday, September 24, 2014

CD tips - Create a custom activity to execute PowerShell scripts in the TFS build process

PowerShell is a powerful scripting language which can be used to customize the behavior of your package deployments. With PowerShell you can add powerful scripting to your build to for example execute a deployment process.
With TFS 2013 hooking up a PowerShell script in the build process is provided out of the box. There are pre- and post-build as well as pre- and post-test hooks. These make customizing build a whole lot easier. You can use these properties to provide the location of the PowerShell script files and the arguments to be used when calling the script as given below



But if you want to integrate a custom action to execute a PowerShell script in the build process other than the out of box properties, you need to create a custom activity for calling a script. To create a custom activity you need to create a new class that inherits from the CodeActivity, which basically gives it a string return value (OutArgument) called Result.
Override the Execute method to add code to call the PowerShell script when this activity is invoked in the build process. You can use the ProcessStartInfo object to invoke the PowerShell script with the arguments as

var info = new ProcessStartInfo(scriptPath,
                String.Format(CultureInfo.InvariantCulture, @"-Version 2.0 {0} {1}", toolPath, parameters));

info.UseShellExecute = false;
info.RedirectStandardOutput = true;
info.RedirectStandardError = true;
info.WindowStyle = ProcessWindowStyle.Hidden;
info.CreateNoWindow = true;

var out = new StringBuilder();
var err = new StringBuilder();
var process = Process.Start(info);

process.OutputDataReceived += (s, e) => { if (String.IsNullOrEmpty(e.Data) == false) { out.AppendLine(e.Data); } };

process.ErrorDataReceived += (s, e) => { if (String.IsNullOrEmpty(e.Data) == false) { err.AppendLine(e.Data); } };

 
process.BeginOutputReadLine();
process.BeginErrorReadLine();
return out.ToString();

Now, to add this activity to a build process, you need to open the build process designer and drag your activity and configure it.

No comments: