Tuesday, April 16, 2019

Powershell + Windows Service : Disable and Stop a Service if it is Enabled and Running.

1. Create Script

2. Create bat file to call Script

3.Schedule Windows task to invoke bat file every (n) minutes

Name: AutoStopStartService.ps1

In my case I am stopping Windows Update, since Win10 likes to restart/re-enable Windows Update it seems every day atleast, even if the Admin disables it!

1. Script: see here

param (

[string]$service = $(throw "-service is required.")

)

write-output 'AutoStopStartService()-> START, svc is $service'

# get service

$ServiceName = $service

$arrService = Get-Service -Name $ServiceName

# get start mode

write-output $arrService.Status

$stu = Get-WmiObject -Class Win32_Service -Property StartMode -Filter "Name='$service'" | Select StartMode;

# if not Disabled, Disable it

if ($stu -NotMatch 'Disabled')

{

write-output 'AutoStopStartService()-> DISABLE it!'

Start-Sleep -seconds 10

set-service $ServiceName -startuptype disabled

}

# if Running, Stop it

if ($arrService.Status -ne 'Running')

{

write-output 'AutoStopStartService()-> Service already stopped!'

}

else

{

write-output 'AutoStopStartService()-> STOP IT!'

Stop-Service $ServiceName

Start-Sleep -seconds 10

$arrService.Refresh()

Write-Host 'Service NEW STATUS-> ' $arrService.Status

}

# done

write-output 'AutoStopStartService()-> DONE'

Exit


2. Create bat file to call Script

powershell .\AutoStopStartService.ps1 -service wuauserv -WindowStyle Hidden

3.Windows Task: Schedule to invoke bat file every (n) minutes

See here

No comments:

Post a Comment