1

I'd like to pipe output from sc query to a method in powershell. For example, checking the status of a service and finding the part that says "STOPPED", and performing an action based on that output.

Is there a way to do this right from the output of sc query? Or do I need to output the results to a text file, and then.. I'm not sure, run a for-loop to find the piece I'm looking for to make an if condition true / false.

This is what I have so far:

Function IsStopped {
    sc.exe query remoteregistry >> RemoteRegistry.txt
    Get-Content -Path C:\RemoteRegistry.txt | Where-Object {$_ -like '*stopped*'} | ForEach-Object {


}

Not sure where to go next?

1 Answer 1

1

PowerShell has a cmdlet for examining services. Running Get-Service without parameters gives you all of the running services in the same way sc.exe does (actually while researching this I reminded myself that in PowerShell sc, without .exe, is an alias for Set-Content, so I ended up generating some useless files. This might be another good reason to use Get-Service to avoid confusion with Set-Content).

Running Get-Service | Get-Member gives a list of the properties and methods from the output of the command. Status is the Property of interest, so we run:

Get-Service | Where-Object { $_.Status -eq 'Stopped' }

The output of this command can then be piped into a for each loop as you have suggested, and each service's properties or methods can be accessed using the $_ shorthand:

Get-Service | Where-Object { $_.Status -eq 'Stopped' } | ForEach-Object {
    Write-Host "Do something with $($_.ServiceName)"
}

It is possible to restart services in this manner, using $_.Start(), but I would recommend writing some error handling into the process if that's your ultimate aim.'

If you need more information, such as the executable, you might want to look here:

How can I extract "Path to executable" of all services with PowerShell

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! Not sure why I thought remote registry was something only accessible by sc. This works for me though, kudos!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.