
close
close
Most of the time, Windows IT pros don’t worry too much about case. For the most part, PowerShell doesn’t care if something is upper case or lower case, and PowerShell commands are not case sensitive. Today, I want to tackle a problem where case does matter to you.
For the my demonstration, I’m going to define a variable with a case-sensitive string.
$var = "I am SOME type of STRING that needs TO BE REVISED: FOO_BAR/TEST"
And I’ll say that this string is representative of many strings that need to be processed. If you wanted to make the entire string lower case, that’s a pretty simple to do
advertisment
$var.ToLower()
You can also make the string upper case:
$var.ToUpper()
Case conversions (Image Credit: Jeff Hicks)
$var.Replace("FOO_BAR","foo_bar")
You can also use the –Replace operator.
advertisment
$var -replace "FOO_BAR","foo_bar"
Both methods will give you the same result.
Replace options (Image Credit: Jeff Hicks)
$text = "Foo_Bar" $var -replace $text.toUpper(),$text.ToLower()
Replacing with variables (Image Credit: Jeff Hicks)
advertisment
$var -match "\w+_\w+"
Matching a regular expression (Image Credit: Jeff Hicks)
$var -replace $Matches.values, $Matches.values[0].toLower()
Replacing with matches (Image Credit: Jeff Hicks)
$var -match "(?<=:\s)\w+(?=\/)"
Using a regex look behind and look ahead (Image Credit: Jeff Hicks)
[regex]$rx = "(?<=:\s)\w+(?=\/)"
I can match the string like this:
Matching with a regex object (Image Credit: Jeff Hicks)
A regex match (Image Credit: Jeff HIcks)
$m = $rx.Match($var) $var -replace $m.Value, $m.value.ToLower()
Replacing with a regex (Image Credit: Jeff Hicks)
$rx.Replace($var,$rx.Match($var).value.toLower())
You’ll get the same result.
It wouldn’t take much more work to put this inside a ForEach loop or using ForEach-Object to process multiple strings.
There’s a lot going on in this article and if you are still new to regular expressions your head might reel a bit. I know mine did when I was getting started with regular expressions. So go ahead. Practice and play. If you’re still stuck or confused, feel free to leave a comment or track me down on Twitter.
More in PowerShell
Microsoft’s New PowerShell Crescendo Tool Facilitates Native Command-Line Wraps
Mar 21, 2022 | Rabia Noureen
Most popular on petri