Display all service names matching a string pattern

I am trying to show the name (only the name) of all installed services containing the string "SQL". For example, I want to see

  • SQLAgent $ SQL2008_R2
  • SQLBrowser
  • SQLWriter

So, I try this:

Get-WmiObject Win32_Service 

Shows all services, but as a list.

 Exit Code : 0 Name : ProtectedStorage ProcessId : 664 StartMode : Manual State : Running Status : OK Exit Code : 1077 Name : QWAVE ProcessId : 0 StartMode : Manual State : Stopped Status : OK (etc...) 

This is good, but I just want to see that name. Therefore, I type:

 Get-WmiObject Win32_Service | select-object Name 

And I get what I expect:

 sppuinotfy SQLAgent$SQL2008_RT SQLBrowser SQLWriter SSDPSRV (etc ..) 

Things are good. I take the following step of filtering names to include only those related to SQL:

 Get-WmiObject Win32_Service | select-object Name | select-string -pattern 'SQL' 

And now this is confusing. Here is my conclusion:

 @{Name=BcmSqlStartupSvc} @{Name=MSOLAP$SQL2008_R2} @{Name=MSSQL$SQL2008_R2} (etc ...) 

Why am I getting this output instead of names? What should I enter to get only names?

+4
source share
3 answers

The easiest way to achieve this is to use the -Filter parameter

 Get-WMIObject Win32_Service -Filter "Name LIKE '%SQL%'" | Select -ExpandProperty Name 

In case you want to use only your code, here is how you can change it:

 Get-WmiObject Win32_Service | Select-Object -ExpandProperty Name | Select-String -pattern 'SQL' 

Edit: the LIKE operator takes several metacharacters to support the corresponding pattern.

[] - to match the range. For example, Name LIKE '[af]%' display all services, starting with any letter from a to f.

^ - no. For example, Name LIKE '[^af]%' will display services that do not start with any letter from a to f.

_ - matches one letter. For example, Name LIKE 'S_L%' will display services starting with S and followed by any letter.

+6
source

You can use Get-Service instead of get-WMIObject and do it like this:

 get-service sql* | select -expand name 
+11
source
 Get-Service | Where-Object {$_.Name -match "SQL"} |Select-Object Name 
+4
source

Source: https://habr.com/ru/post/1336077/


All Articles