How to ensure IIS website is completely stopped in Powershell?
<p>I've got a Powershell script that stops an IIS website and corresponding app pool and then deletes the app logs (log4net logs). Here is the script snippet:</p>

<pre><code>stop-website -name "MyWebsite"
stop-webapppool -name "MyWebsite"
del c:\inetpub\MyWebsite\logs\*.*
</code></pre>

<p>The problem is stop-website and stop-webapppool seem to return before the website is completely shutdown which results in the delete failing saying the file is being used by another process:</p>

<blockquote>
  <p>del : Cannot remove item C:\inetpub\MyWebsite\logs\App.log: The process cannot access the file 'C:\inetpub\MyWebsite\logs\App.log' because it is being used by another process.</p>
</blockquote>

<p>If I add a 10 second sleep between the stop commands and the del command then the logs are deleted successfully. This is very hackish though and not reliable. Is there a way to force the stop-website/stop-webapppool commands to not return until the website/apppool is completely stopped?</p>

<p>Thanks.</p>

<hr>

<p>Implemented solution from the below link. I will wait ~60 seconds and then kill the IIS process if it hasn't stopped.</p>

<p><a href="https://greenfinch.ie/blog/powershellscript.html" rel="noreferrer">https://greenfinch.ie/blog/powershellscript.html</a></p>

<pre><code>        "Stopping IIS site [$name]" &gt;&gt; $logFile
        stop-website -name $name

        "Stopping app pool [$name]" &gt;&gt; $logFile
        stop-webapppool -name $name

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

            if ($sleepTime -gt 60)
            {
                "Waited [$sleepTime] sec for process [$processId] to stop and it is still running. Killing it." &gt;&gt; $logFile
                Stop-Process $processId
                break
            }

            if ($processId)
            {
                "App pool [$name] is running with process ID: [$processId]. Sleeping for [$sleepTime] sec and then checking again." &gt;&gt; $logFile
                Start-Sleep -s $sleepTime
                $sleepTime = $sleepTime + 10
            }
        }
</code></pre>