locked
Trim a string removes more than what I want RRS feed

  • Question

  • I have a service with the DisplayName attribute like this

    PS C:\> (Get-Service -Name 'VismaBusinessServicesHost(*)').DisplayName
    Visma Business Services Host (S31000)

    Then I try to trim this so i only get the part inside ()

    PS C:\> (Get-Service -Name 'VismaBusinessServicesHost(*)').DisplayName.TrimStart("Visma Business Services Host (").TrimEnd(")")
    31000

    But this also removes the S in front of 31000, which I really need

    Why does this happen?


    Freddy

    Wednesday, August 17, 2016 11:43 AM

Answers

  • Hello,

    The reason is that TrimStart accepts an Array of Char and not a string, so it will remove each occurrence of every symbol you give it in the string. So as "S" is in that array it removes it from your output. As suggested above, you should use Replace instead of TrimStart:

    Get-Service -Name 'VismaBusinessServicesHost(*)').DisplayName.Replace("Visma Business Services Host (","").Replace(")","")
    Regards


    • Marked as answer by CesarTabares Wednesday, August 17, 2016 2:20 PM
    • Edited by Avendil Wednesday, August 17, 2016 2:59 PM
    Wednesday, August 17, 2016 12:10 PM

All replies

  • Have you tried to do a replace instead?

    (Get-Service -Name 'VismaBusinessServicesHost(*)').DisplayName.Replace("(","").Replace(")","")


    If you find that my post has answered your question, please mark it as the answer. If you find my post to be helpful in anyway, please click vote as helpful.

    Wednesday, August 17, 2016 11:54 AM
  • No, I haven't. Why can't I use Trim?

    Freddy

    Wednesday, August 17, 2016 11:59 AM
  • This works:

    (Get-Service -Name 'VismaBusinessServicesHost(*)').DisplayName -match '\((.*)\)'
    $matches[1]


    \_(ツ)_/

    Wednesday, August 17, 2016 12:02 PM
  • (Get-Service -Name 'VismaBusinessServicesHost(*)').DisplayName -replace '.*\(|\)'

    • Proposed as answer by jrv Wednesday, August 17, 2016 12:09 PM
    • Unproposed as answer by CesarTabares Wednesday, August 17, 2016 2:20 PM
    Wednesday, August 17, 2016 12:06 PM
  • Wednesday, August 17, 2016 12:07 PM
  • Hello,

    The reason is that TrimStart accepts an Array of Char and not a string, so it will remove each occurrence of every symbol you give it in the string. So as "S" is in that array it removes it from your output. As suggested above, you should use Replace instead of TrimStart:

    Get-Service -Name 'VismaBusinessServicesHost(*)').DisplayName.Replace("Visma Business Services Host (","").Replace(")","")
    Regards


    • Marked as answer by CesarTabares Wednesday, August 17, 2016 2:20 PM
    • Edited by Avendil Wednesday, August 17, 2016 2:59 PM
    Wednesday, August 17, 2016 12:10 PM