Manipulate Text: Convert [BEGIN ] to Begin

I continue to say the same thing around here, and I suspect I’ll continue to do so. I use my site to record things I’m going to want to find quickly one day. While this is going to be a short post, it’s going to hold a few lines of PowerShell code I don’t want to rewrite some other afternoon. This isn’t to say it difficult by any means. It’s meant to say, that my time is better spent learning than relearning all over again. Bonus, there’s a good chance this might help someone else out too!

I’m right in the middle of improving my 2.1 version of my Advanced Function Template. For each block it enters (Begin, Process, and End), it needs to turn this string, for example, “[BEGIN  ]” into this this string, “Begin.”

To do that, we need to remove the square brackets, remove the spaces after the word BEGIN, and finally make “EGIN” lowercase. Not terribly complex, but worth the five minutes it takes to write and publish this post. And with that, the code.

Remove-Variable x -ErrorAction SilentlyContinue

$x = '[BEGIN  ]'
"1st: $x - No edits."

$x = $x.Trim(' []')
"2nd: $($x.Length) - Length proves spaces/brackets removed."

"3rd: $($x.Substring(0,1)) - First letter only."

"4th: $($x.Substring(1,($x.Length-1))) - All letters but first."

"5th: $($x.Substring(1,($x.Length-1)).ToLower()) - All letters but first (lowercase)."

$x = $x.Substring(0,1)+$x.Substring(1,($x.Length-1)).ToLower()
"6th: $x - Done."

1st: [BEGIN  ] - No edits.
2nd: 5 - Length proves spaces/brackets removed.
3rd: B - First letter only.
4th: EGIN - All letters but first.
5th: egin - All letters but first (lowercase).
6th: Begin - Done.

Enjoy the weekend.

3 thoughts on “Manipulate Text: Convert [BEGIN ] to Begin

    1. tommymaynard Post author

      This is helpful, however, BEGIN won’t always be BEGIN. Sometimes it’s PROCESS, and sometimes it’s END. Good thinking, however. I didn’t even consider the replace comparison operator.

      Reply

Leave a Reply

Your email address will not be published.