Munging Strings in Windows PowerShell – Part Two

In my post yesterday we glimpsed a PowerShell code fragment to transform each character in a string to the previous or next letter in the alphabet.  Let’s dive just a touch deeper – more like just sticking our big toe in the water – looking at what these lines of code do.

Let’s work from the inside out.

“EXCHANGE12ROCKS”.ToCharArray()

This merely takes the string literal “EXCHANGE12ROCKS” and uses the string method ToCharArray() to convert it to a character array.

%{ [char]([int]($_)+1) }

Next, that character array is sent down a pipeline to the above ForEach-Object loop, with the percent sign (%) alias to the ForEach-Object cmdlet being used here.  For each character, $_, we convert it to an integer, add one, then convert it back into a character. That’s the heart of our chrazy translation in this example responsible for changing “A” to “B”, “2” to “3”, or “S” to “T.”  Note that the subtraction form is only one character different.

new-object string (,(…))

The final bit of magic lay in the use of the new-object cmdlet to convert the intermediately resultant character array back into a character string. In the snippet shown above, the aforementioned pipeline is replaced with an ellipsis for brevity and clarity. It’s important to note that the inner set of parentheses indicates that the pipeline value is to be used as an argument to the comma operator, while the outer set of parentheses makes sure that the result of the comma operator is used as the one value for the parameter after the “string” class name.

So how could you modify this to do something useful? That’s an interesting question, but instead let’s answer how it could do something marginally humorous in closing. How could we make a function (although a filter would be more fun) out of this sort of code to allow quick manipulations on names?

# Function to increment each character in a string

function increment-string( $str, $inc = +1 ){

return new-object string `

(,($str.ToCharArray() | %{ [char]([int]($_)+$inc) }))

}

All that has been changed from the fixed examples is that the string has been parameterized and the amount to increment or decrement by has been parameterized as well. Consider the following examples.

increment-string “VMS”

Which should yield “WNT,” and:

increment-string “IBM” -1

which should result in “HAL.”

What can this function do with your name? With product names? How about using +3, -12, or other offsets? Can you modify the function to wrap (rotate) within the alphabetic, numeric, or symbol parts of the character set? Can you change it from a function to a filter which accepts pipeline input? What would { gwmi win32_operatingsystem | rotate-string +13 } result in? Can you think of any useful purpose for such string operations as incrementing and decrementing characters?

-Brad Werner

In this article

Join the Conversation