How to ensure IIS website is completely stopped in Powershell?

The simplest way to stop the app pool and get it into Stopped state is to use appcmd.exe. It will return when the app pool is really stopped or you'll get an error

Just do this on PowerShell:

& $env:windir\system32\inetsrv\appcmd.exe stop apppool /apppool.name:"YourAppPoolName"

When your AppPool is correctly stooped you'll get this message:

"YourAppPoolName" successfully stopped


You can use these two commands to check the status of the website/app, say after 10 seconds, then use an If statement to delete logs only when the status returned is stopped

Get-WebsiteState -name "MyWebsite"
Get-WebAppPoolState -name "MyWebsite"

This loop should help you too

$currentRetry = 0;
$success = $false;
do{
    $status = Get-WebAppPoolState -name "MyWebsite"
    if ($status -eq "Stopped"){
         <....your code here....>
            $success = $true;
        }
        Start-Sleep -s 10
        $currentRetry = $currentRetry + 1;
    }
while (!$success -and $currentRetry -le 4)

Updated Apr 24, 2019

Based on comment and current cmdlet document, it appears the return type is indeed an object. Thus presumably can be handled as commented or the line snippet below. Author no longer have access to Windows Server environment therefore did not directly modify original answer nor able to test the update

if ($status.Value -eq "Stopped")

After you run 'Stop-WebAppPool' the state of the WebAppPool will be "Stopping" and it may take a few seconds before the state of the WebAppPool is actually "Stopped".
Here is a little function to help with the WebAppPoolState

function Stop-AppPool ($webAppPoolName,[int]$secs) {
$retvalue = $false
$wsec = (get-date).AddSeconds($secs)
Stop-WebAppPool -Name $webAppPoolName
Write-Output "$(Get-Date) waiting up to $secs seconds for the WebAppPool '$webAppPoolName' to stop"
$poolNotStopped = $true
while (((get-date) -lt $wsec) -and $poolNotStopped) {
    $pstate =  Get-WebAppPoolState -Name $webAppPoolName
    if ($pstate.Value -eq "Stopped") {
        Write-Output "$(Get-Date): WebAppPool '$webAppPoolName' is stopped"
        $poolNotStopped = $false
        $retvalue = $true
    }
}
return $retvalue
}

you can run this function using e.g.

Stop-AppPool "MyWebsite" 30

and check the return-value to see if the WebAppPool has stopped within the given seconds

Tags:

Iis

Powershell