How to Remove Orphaned Services Using PowerShell

by Doug Finke on April 7, 2010

SC is a command line program used for communicating with the Service Control Manager and services.

This snippet demonstrates how PowerShell automates existing command line programs. SC doesn’t take wild cards for the service name parameter nor does it take an array of servers to act on.

Quickly and Easily remedied using PowerShell.

On Your Local Computer

The Get-Service gets the services on a local or remote computer.

Get-Service YourService* |             
    ForEach { C:\WINDOWS\system32\sc.exe delete $_.DisplayName }

Across Several Computers

Notice the different formats needed for ComputerName by the Get-Service cmdlet and SC program. With and without the backslashes.

Function ql {$args}            
            
ForEach($computerName in (ql Machine1 Machine2 Machine3)) {            
    Get-Service YourService* -ComputerName $computerName |             
        ForEach {             
            C:\WINDOWS\system32\sc.exe `
                "\\${computerName}" delete $_.DisplayName             
        }             
}

PowerShell Remoting

An alternative approach is PowerShell remoting using Invoke-Command. One con, there is overhead to authenticate with each remote server.

On the plus side you can use the –AsJob parameter which runs the command as a background job on a remote computer. Then you’ll need to add code to harvest the results.

Function ql {$args}            
            
ForEach($computerName in (ql Machine1 Machine2 Machine3)) {            
    Invoke-Command -ComputerName $computerName -ScriptBlock {            
        Get-Service YourService* |             
            ForEach {             
                C:\WINDOWS\system32\sc.exe delete $_.DisplayName             
            }             
    }            
}

{ 1 trackback }

Tweets that mention How to Remove Orphaned Services Using PowerShell -- Topsy.com
04.08.10 at 1:35 pm

{ 2 comments… read them below or add one }

-phil 05.03.10 at 5:57 pm

ah, so! i wonder what stitch in our side this one came from ;) now if only the service manager would not take it’s sweet time with the automated requests.

Doug Finke 05.03.10 at 7:48 pm

You know it.

Leave a Comment

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>