Your basic ITPro blog... What's going on at work, what I'm interested in.

Monday, April 14, 2008

Service Management using PowerShell and WMI

PowerShell has some great cmdlets for managing services (Get-, New-, Restart-,Resume-, Set-, Start-, Stop-, and Suspend-Service). The problem is that with V1 of PowerShell, you can't run these against remote computers. Luckily though, we have complete access to WMI from within PowerShell. So, the seemingly impossible quickly becomes quite easy.

My task today was to find a series of services on multiple computers and both Disable and Shutdown these services. Of course, I could have gone to each computer and, using the Services MMC snap-in, disabled and shutdown these services. A little tedious, but doable. Not a big deal if you only have to do this on a few computers. But, imagine needing to do this on dozens or more.

Scripting this job made it much easier. And the great thing is that, once we are ready to, I can tweak this script and quickly re-enable these services.

## Stop-LandeskServices.ps1
## 2008-04-14
## Reads a list if computers from a text file
## For each computer,
##   Stops and disables the five Landesk services


$computers = Get-Content '.\computerList.txt'

foreach ($computer in $computers) {
    Write-Host "`nNow processing computer: $computer"
    $services = Get-WmiObject win32_service -computer $computer | `
        where {$_.Name -eq 'LDXDD' `
        -or $_.Name -eq 'ISSUSER' `
        -or $_.Name -eq 'Intel Targeted Multicast' `
        -or $_.Name -eq 'CBA8' `
        -or $_.Name -eq 'softmon'}
    foreach ($service in $services) {
        Write-Host "... processing service:" $service.Name "... stopping... " -NoNewline 
        $null = $service.StopService()
        Write-Host "disabling..." -NoNewline 
        $null = $service.ChangeStartMode("Disabled")
        Write-Host " DONE!"

No comments:

Additional Info

My photo
email: support (AT) mangrumtech (DOT) com
mobile: 480-270-4332