Reputation: 167
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?
Upvotes: 1
Views: 1735
Reputation: 5452
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
Upvotes: 1