Script to keep service stopped

While installing SharePoint 2007 SP2, it is advised to stop the W3SVC service to prevent end users from connecting to the web applications.  Since our services are governed by group policies, it could be that the W3SVC service would restart in the middle of the upgrade process due to the application of the GPO’s (by default every 90 minute I believe).  To prevent this, I wrote this little script that stops the W3SVC, and keeps monitoring it, stopping it every time it tries to start.

# KeepServiceStopped.ps1
# Created by Bert Van Landeghem 
# 21/06/2010 

param(
    $serviceName = "W3SVC"
)

write-host -ForegroundColor cyan "This script will stop the $($serviceName) service."
write-host -ForegroundColor cyan "It will continue to run, monitoring the service, and stopping it every time it tries to start."
write-host -ForegroundColor cyan "Press any key to stop the script and restart the service."

do { $choice = Read-Host -Prompt "Would you like to continue? [y|n]" }
until ( $choice -match "y|n" )

Switch ($choice)
{
    "n" {exit}
    "y" {
        sleep -m 500
        $Host.UI.RawUI.FlushInputBuffer()
        while ( -not $host.ui.RawUI.KeyAvailable  )
        {
            Get-Service -Name $serviceName `
                | where-object{ $_.status -eq "running" } `
                | %{Stop-Service -Name $_.Name -passthru} `
                | %{Write-Host "$($_.name) Stopped at $(get-date)."}
            sleep -m 1000
        }
    }
}

Get-Service -Name $serviceName `
    | ?{ $_.status -eq "Stopped" } `
    | %{Start-Service $_.Name -passthru} `
    | %{Write-Host "$($_.name) started at $(get-date)."}

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s