MSBuild Kill Application Pool Process c#

Needed to kill an application pool process using an MSBuild task and C# cos the process was locking a file.

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Microsoft.Build.Utilities;
using Microsoft.Build.Framework;
using System.Diagnostics;
using System.Management;

namespace MyProject.Deployment.Tasks
public class AppPoolKillProcess : Task
const string logMessage = "Process Kill: {0}, for Application Pool: {1}";
const string query = "select * from Win32_Process where Name = 'w3wp.exe'";
const string logAppPoolNotFound = "Application Pool named '{0}' not found.";

public string ApplicationPool { get; set; }

public string ComputerName { get; set; }

private ManagementObjectSearcher objSearcher = new ManagementObjectSearcher(query);

public override bool Execute()

bool appPoolFound = false;
ConnectionOptions connOptions = new ConnectionOptions();
connOptions.Impersonation = ImpersonationLevel.Impersonate;
connOptions.EnablePrivileges = true;
ManagementScope manScope = new ManagementScope(String.Format(@"\\{0}\ROOT\CIMV2", this.ComputerName), connOptions);

SelectQuery objQuery = new SelectQuery(query);
ManagementObjectSearcher searcher = new ManagementObjectSearcher(manScope, objQuery);
ManagementObjectCollection searcherObjCollection = searcher.Get();

foreach (ManagementObject searchObj in searcherObjCollection)
//The Commandline property contains the application pool name.
if (searchObj["CommandLine"].ToString().Contains(this.ApplicationPool))

appPoolFound = true;
Log.LogMessage(MessageImportance.High, String.Format(logMessage, searchObj["ProcessId"].ToString(), searchObj["CommandLine"].ToString()));
object[] obj = new object[] { 0 };

searchObj.InvokeMethod("Terminate", obj);

//If not application pool found, then send a message to diagnostic.
if (!appPoolFound) Log.LogMessage(MessageImportance.High, string.Format(logAppPoolNotFound, this.ApplicationPool));

return true;




About jpadda

Technical Consultant currently working as part of the .Net team for EMC Consulting.
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s