TFS Release Manager–Website Application Pool Start & Stop

Requirement is to copy the updated files of the website to the target environment (Production, Staging etc.) automatically using copy task in release manager.

It can be easily implemented by using the copy task which is internally a Robocopy operation.

Issue is that the copy task will fail, if some user is already accessing the website and at the same time this task is trying to copy the files.

This problem can be handled by implementing following steps in the given order –

  1. Stop the application pool
  2. Copy the updated web files
  3. Start the application pool

Step 2 above is the available copy task in TFS RM.

Step 1 and 3 can be implemented using a PowerShell script.

Here is the content of the script –

<#

.Synopsis
Start / Stop Application Pool

.Discription
It starts or stops the application pool of a website.

.Example
powershell.exe -file .\AppPoolStopStart.ps1 ApplicationPoolName Start/Stop

. Example
powershell.exe -file .\AppPoolStopStart.ps1 DefaultAppPool Start

#>

param ([parameter(Mandatory=$True,Position=0)]
[string][ValidateNotNullOrEmpty()]$AppPoolName,

[Parameter(Mandatory=$true, Position=1)]
[string][ValidateNotNullOrEmpty()]$Action)


if ($Action -eq "stop")
{
Write-Output "Stoping the Application Pool - ($AppPoolName)......."
import-module WebAdministration
if((Get-WebAppPoolState $AppPoolName).Value -ne 'Stopped')
{
Stop-WebAppPool -Name $AppPoolName
Write-Output "Application Pool - ($AppPoolName) stopped successfully!"
}
}

if ($Action -eq "start")
{
Write-Output "Starting the Application Pool - ($AppPoolName)......."
import-module WebAdministration
if((Get-WebAppPoolState $AppPoolName).Value -ne 'Started')
{
Start-WebAppPool -Name $AppPoolName
Write-Output "Application Pool - ($AppPoolName) started successfully!"
}
}

Its can be executed as -  .\AppPoolStopStart.ps1 DefaultAppPool Start

Now add this to the source code in TFS and publish it in the build artifacts for the release definition.

In release definition, add the following tasks in the below order –

  1. Task to copy this PowerShell from the published artifacts to the target machine.
  2. Task to run PowerShell on Target Machines to execute the above PS script with an arguments as “Application Pool Name and the status as “Stop”. image
  3. Other required Release Manager tasks.
  4. Task to run PowerShell on Target Machines to execute the above PS script with an arguments as “Application Pool Name and the status as “Start”. 

           image

On successful execution of the above release definition, it will –

  1. First stop the application pool. image
  2. After successful execution of other tasks, it will finally start the application pool.image

             ——End of Article——