0

I am running below PowerShell command to lookup a specific windows service.

Get-WMIObject Win32_Service | Where-Object {$_.name -like "HyS9FinancialManagementJavaServer_*" }|select name

which gives me expected output of

HyS9FinancialManagementJavaServer_epmsystem1.

My requirement is get only the string after _. Is there a way to achieve this in PowerShell?

Abra
  • 19,142
  • 7
  • 29
  • 41
ajay k
  • 59
  • 6
  • 2
    You can use `-replace '.*_'` to remove everything up to and including the _. `(Get-WMIObject Win32_Service | Where-Object { $.name -Like 'HyS9FinancialManagementJavaServer*' } | Select-Object -ExpandProperty Name ) -replace '.*_'` – Daniel Jun 04 '22 at 05:39
  • Getting below error while trying the above command. $.name : The term '$.name' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:47 + (Get-WMIObject Win32_Service | Where-Object { $.name -Like 'HyS9Finan ... + ~~~~~~ + CategoryInfo : ObjectNotFound: ($.name:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException – ajay k Jun 04 '22 at 05:55
  • Sorry, copy and paste error from your code :) Correct `$.name` to `$_.name` --- `(Get-WMIObject Win32_Service | Where-Object { $_.Name -Like 'HyS9FinancialManagementJavaServer*' } | Select-Object -ExpandProperty Name ) -replace '.*_'` – Daniel Jun 04 '22 at 05:57
  • 1
    @Daniel May I suggest _anchoring_ your pattern? `^.*_` – Theo Jun 04 '22 at 08:53
  • @Theo, to show intent I think that makes sense, but in practice is there any situation that not anchoring `.*` will not match everything from the start of the line? – Daniel Jun 04 '22 at 18:29

2 Answers2

1

Try Name, Expression option while selecting

Get-WMIObject Win32_Service | Where-Object {$_.name -like "HyS9FinancialManagementJavaServer_*" }|Select-Object @{n="Name";e={(([String]($_.Name)).Split('_'))[1]}}
0

First, the obligatory advice:

  • The CIM cmdlets (e.g., Get-CimInstance) superseded the WMI cmdlets (e.g., Get-WmiObject) in PowerShell v3 (released in September 2012). Therefore, the WMI cmdlets should be avoided, not least because PowerShell (Core) v6+, where all future effort will go, doesn't even have them anymore. Note that WMI still underlies the CIM cmdlets, however. For more information, see this answer.

That said, given that you're seemingly targeting the local machine's services, using
Get-Service, which directly accepts wildcard-based name patterns, is simpler.

(Get-Service HyS9FinancialManagementJavaServer_*).Name -replace '^.+_'

Note the use of the regex-based -replace operator to strip everything up to and including the (last) _ (regex ^.+_) from (each) name.

mklement0
  • 382,024
  • 64
  • 607
  • 775