Working with services is quite common action for any windows administrators. In this post, we will see how to set a list of services to disabled state in remote computers using PowerShell.
Often system administrators get requirement to disable services on list of remote computers. This script will help such admins who are having similar requirement. This script is a simple wrapper based on Get-WMIObject query and Set-Service cmdlets. The advantage with Get-WMIObject is that it can give you the startup mode of a give services. Neither Get-Service nor any other approach(except sc.exe) gives you this information. So I always feel comfortable calling Win32_Service WMI class with Get-WMIObject cmdlets as it returns major set of information. However service objects obtained via Get-WMIObject lagging facility to set a service to disabled. That is when Set-Service cmdlets comes handy. This is one of the less exposed cmdlets – I don’t see many people using this. Rather everyone relying on calling sc.exe from PowerShell.
This script takes two arguments.
- ComputerName : you can pass single or multiple computernames to this parameter as a comma separated. If this parameter is not specified, script works against local computer.
- ServiceName : This is a mandatory parameter where you need to give list of services that you want to stop and disable.
Code
[cmdletbinding()]
param(
[string[]]$ComputerName = $env:ComputerName,
[parameter(Mandatory=$true)]
[string[]]$ServiceName
)
foreach($Computer in $ComputerName)
{
Write-Host "Working on $Computer"
if(!(Test-Connection -ComputerName $Computer -Count 1 -quiet)) {
Write-Warning "$computer : Offline"
Continue
}
foreach($service in $ServiceName)
{
try
{
$ServiceObject = Get-WMIObject -Class Win32_Service -ComputerName $Computer -Filter "Name='$service'" -EA Stop
if(!$ServiceObject)
{
Write-Warning "$Computer : No service found with the name $service"
Continue
}
if($ServiceObject.StartMode -eq "Disabled")
{
Write-Warning "$Computer : Service with the name $service already in disabled state"
Continue
}
Set-Service -ComputerName $Computer -Name $service -EA Stop -StartMode Disabled
Write-Host "$Computer : Successfully disabled the service $service. Trying to stop it"
if($ServiceObject.state -eq "Stopped")
{
Write-Warning "$Computer : $service already in stopped state"
Continue
}
$retval = $ServiceObject.StopService()
if($retval.ReturnValue -ne 0)
{
Write-Warning "$Computer : Failed to stop service. Return value is $($retval.ReturnValue)"
Continue
}
Write-Host "$Computer : Stopped service successfully"
} catch
{
Write-Warning "$computer : Failed to query $service. Details : $_"
Continue
}
}
}
Output
The output of the script is a simple text with the status of disabling & stopping each service.
Hope this helps…