Powershell - Trim

Hi to all,

I am trying to find out away how to trim a string from a specific character.

let say I have a package name: Baybon_v1.0

How can I trim this to show only: Babylon

Another example:

Microsoft office professional_v2016

Would like to trim the text starting β€œ_”

The result should be:

Microsoft office professional

Thank you so much for your time and help

Amir :slight_smile:


This example is hardcoded but it works

[string] $str1 = "Baybon_v1.0"


OUTPUT = Baybon

$str1 = "Microsoft office professional_v2016"


OUTPUT = Microsoft office professional


If you want this to be generic, such as function that works for all cases, consider wildcards or regexes in

combination with String.Trim()

<p style=β€œtext-align: left;”>Another option would be to use Split. You can split string by specific character and create array.</p>
On you case you will split by _ and will use the first element of that array.

$str1 = "Baybon_v1.0"


Hope that helps

Few more options

$text = 'Microsoft office professional_v2016'

$text -replace '_.+'

$text -split '_' | select -First 1

($text -split '_')[0]

If($text -match '.+(?=_)'){$matches.0}

WOW… i never thought there are so may ways to do one complex task :slight_smile:

Thank you guys :slight_smile: