Blog

"Knowledge has no value unless you use it and share it"

Automated Deployment: PowerShell Script to Stop IIS Website

The Problem

One of our products contains an IIS web application which uses long-running threads to process background tasks. Unfortunately this can make it a little tricky to deploy a new version of the product.

Back when we used to manually deploy our applications, we would manually stop the app pool for this particular web application. Then we would deliberately wait until all of the processes had completed, before installing the new version. Depending on the time of day, this could take several minutes.

A while back, we started investing in automated deployment (hurray!!!). This involved introducing PowerShell scripts to stop, start, install and uninstall our IIS websites.

Unfortunately for us, the Stop-WebAppPool PowerShell function in the WebAdminstration module is asynchronous. Which meant that our scripts were trying to install a new version of the application before the IIS process had fully come to an end. This resulted in a big PowerShell exception and a failed deployment (boo-urns!!)

The Solution

Fortunately, we were able to solve our issue by extending our deployment script to wait until the IIS process has finished before proceeding with the deployment.

The PowerShell code looks something like this:

Import-Module WebAdministration

function Stop-IisWebsiteGracefully([string]$appPoolName) Write-Debug "Stopping app pool '$appPoolName'..."
    Stop-WebAppPool -Name $appPoolName

    $processId =
        Get-WmiObject -Class win32_process -filter "name='w3wp.exe'" |
            ?{ ($_.CommandLine).Split("`"")[1] -eq $appPoolName } |
            %{ $_.ProcessId }

    if ($processId) {
        Write-Warning "App pool '$appPoolName' is running with process ID: '$processId'."
        Write-Warning "Waiting up to 5 minutes for process to finish..."
        Wait-Process -Id $processId -Timeout 300 -ErrorAction Stop
    }

    Write-Debug "Stopping app pool '$appPoolName' - DONE!"
}

Happy Coding!

A Final Word

As you can see, at Greenfinch Technology coding is what we are great at. We are always actively working to keep up with the latest trends in technology and new coding languages. In our opinion. to stand still is to fall behind. You can be sure we have no intention of letting that happen to either ourselves or to our clients.

If you would like a modern, forward-thinking IT company to help with your custom enterprise software solutionsweb or mobile app development, a BPM such as Siskin or any Cloud technologies please feel free to contact us at 01 818 2949 or email us using our contact form. We will help guide you safely through the process of advancing your company beyond your competitors.

VIEW ALL BLOGS