Reverse Strings with PowerShell

Doctor Scripto

Summary: Ed Wilson, Microsoft Scripting Guy, talks about using Windows PowerShell to reverse strings.

Hey, Scripting Guy! Question Hey, Scripting Guy! I am working with Windows PowerShell, and I need to reverse a string. I am surprised there is no reverse method in the string class. It seems like a major oversight. Anyway, can you show me how to do this easily?

—SS

Hey, Scripting Guy! Answer Hello SS,

Microsoft Scripting Guy, Ed Wilson, is here. This week is an awesome week. The MVP Summit is going on, and the Scripting Wife is in Bellevue/Redmond/Seattle hanging with thousands of MVPs from around the world. She keeps sending me text messages, like, “Dude, I just got to see Jaap,” and “I was talking to Mark,” and “Guess what? Karl is coming to the get-together tonight.” One was, “You are not going to believe it. Vlad invited me to sit in on the Jeremy unplugged session! OMG!!!”

I mean, it is nearly a real-time stream of messages. Then she goes quiet when she is in an NDA session.

Nah, I am not jealous. Nope. Not one bit…

So, SS. I was sitting on the patio overlooking the pool, and I was sipping a nice cup of English Breakfast tea. I have rather poor WiFi, but I turned on Internet Connection Sharing on my Windows 8.1 phone, and boom! My Windows 10 laptop joined the connection and all is good. Actually, the performance is really quite good. I might watch Buffy the Vampire Slayer this evening on Netflix. Yeah, no reason not to. This is working out really well. I digress…

So you have a string. I’ll store the string in a variable named $a. I then display the contents of the $a variable. This is shown here:

PS d:\> $a = “abcde”

PS d:\> $a

Abcde

I know that I have a System.String, and I can look this up by using the Get-Member cmdlet. I pipe the $a variable to Get-Member (gm is an alias) and look through the methods and properties associated with the string object:

PS d:\> $a | gm

   TypeName: System.String

Name             MemberType            Definition

—-                 ———-                  ———-

Clone            Method                System.Object Clone(), System.Object ICloneable.Clone()

CompareTo        Method                int CompareTo(System.Object value), int CompareTo(string strB), int IComparab…

Contains         Method                bool Contains(string value)

CopyTo           Method                void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int co…

EndsWith         Method                bool EndsWith(string value), bool EndsWith(string value, System.StringCompari…

Equals           Method                bool Equals(System.Object obj), bool Equals(string value), bool Equals(string…

GetEnumerator    Method                System.CharEnumerator GetEnumerator(), System.Collections.IEnumerator IEnumer…

GetHashCode      Method                int GetHashCode()

GetType          Method                type GetType()

GetTypeCode      Method                System.TypeCode GetTypeCode(), System.TypeCode IConvertible.GetTypeCode()

IndexOf          Method                int IndexOf(char value), int IndexOf(char value, int startIndex), int IndexOf…

IndexOfAny       Method                int IndexOfAny(char[] anyOf), int IndexOfAny(char[] anyOf, int startIndex), i…

Insert           Method                string Insert(int startIndex, string value)

IsNormalized     Method                bool IsNormalized(), bool IsNormalized(System.Text.NormalizationForm normaliz…

LastIndexOf      Method                int LastIndexOf(char value), int LastIndexOf(char value, int startIndex), int…

LastIndexOfAny   Method                int LastIndexOfAny(char[] anyOf), int LastIndexOfAny(char[] anyOf, int startI…

Normalize        Method                string Normalize(), string Normalize(System.Text.NormalizationForm normalizat…

PadLeft          Method                string PadLeft(int totalWidth), string PadLeft(int totalWidth, char paddingChar)

PadRight         Method                string PadRight(int totalWidth), string PadRight(int totalWidth, char padding…

Remove           Method                string Remove(int startIndex, int count), string Remove(int startIndex)

Replace          Method                string Replace(char oldChar, char newChar), string Replace(string oldValue, s…

Split            Method                string[] Split(Params char[] separator), string[] Split(char[] separator, int…

StartsWith       Method                bool StartsWith(string value), bool StartsWith(string value, System.StringCom…

Substring        Method                string Substring(int startIndex), string Substring(int startIndex, int length)

ToBoolean        Method                bool IConvertible.ToBoolean(System.IFormatProvider provider)

ToByte           Method                byte IConvertible.ToByte(System.IFormatProvider provider)

ToChar           Method                char IConvertible.ToChar(System.IFormatProvider provider)

ToCharArray      Method                char[] ToCharArray(), char[] ToCharArray(int startIndex, int length)

ToDateTime       Method                datetime IConvertible.ToDateTime(System.IFormatProvider provider)

ToDecimal        Method                decimal IConvertible.ToDecimal(System.IFormatProvider provider)

ToDouble         Method                double IConvertible.ToDouble(System.IFormatProvider provider)

ToInt16          Method                int16 IConvertible.ToInt16(System.IFormatProvider provider)

ToInt32          Method                int IConvertible.ToInt32(System.IFormatProvider provider)

ToInt64          Method                long IConvertible.ToInt64(System.IFormatProvider provider)

ToLower          Method                string ToLower(), string ToLower(cultureinfo culture)

ToLowerInvariant Method                string ToLowerInvariant()

ToSByte          Method                sbyte IConvertible.ToSByte(System.IFormatProvider provider)

ToSingle         Method                float IConvertible.ToSingle(System.IFormatProvider provider)

ToString         Method                string ToString(), string ToString(System.IFormatProvider provider), string I…

ToType           Method                System.Object IConvertible.ToType(type conversionType, System.IFormatProvider…

ToUInt16         Method                uint16 IConvertible.ToUInt16(System.IFormatProvider provider)

ToUInt32         Method                uint32 IConvertible.ToUInt32(System.IFormatProvider provider)

ToUInt64         Method                uint64 IConvertible.ToUInt64(System.IFormatProvider provider)

ToUpper          Method                string ToUpper(), string ToUpper(cultureinfo culture)

ToUpperInvariant Method                string ToUpperInvariant()

Trim             Method                string Trim(Params char[] trimChars), string Trim()

TrimEnd          Method                string TrimEnd(Params char[] trimChars)

TrimStart        Method                string TrimStart(Params char[] trimChars)

Chars            ParameterizedProperty char Chars(int index) {get;}

Length           Property              int Length {get;}

I see that there are also some static members that have been added:

PS d:\> $a | gm -Static

   TypeName: System.String

Name               MemberType      Definition

—-                    ———-            ———-

Compare            Method     static int Compare(string strA, string strB), static int Compare(string strA, string s…

CompareOrdinal     Method     static int CompareOrdinal(string strA, string strB), static int CompareOrdinal(string …

Concat             Method     static string Concat(System.Object arg0), static string Concat(System.Object arg0, Sys…

Copy               Method     static string Copy(string str)

Equals             Method     static bool Equals(string a, string b), static bool Equals(string a, string b, System….

Format             Method     static string Format(string format, System.Object arg0), static string Format(string f…

Intern             Method     static string Intern(string str)

IsInterned         Method     static string IsInterned(string str)

IsNullOrEmpty      Method     static bool IsNullOrEmpty(string value)

IsNullOrWhiteSpace Method     static bool IsNullOrWhiteSpace(string value)

Join               Method     static string Join(string separator, Params string[] value), static string Join(string…

new                Method     string new(System.Char*, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b7…

ReferenceEquals    Method     static bool ReferenceEquals(System.Object objA, System.Object objB)

Empty              Property   static string Empty {get;}

The first thing I want to do is to break the string into an array of characters—a character array. Luckily, there is a string method that does just that. I will store the character array in a new variable, $b:

PS d:\> $b = $a.ToCharArray()

PS d:\> $b

a

b

c

d

e

So, now I want to reverse the character array. To do this, I use the static reverse method from the [array] object:

PS d:\> [array]::Reverse($b)

PS d:\> $b

e

d

c

b

a

   Note  The cool thing here is that the array reverses order. I do not need to save the output in a new variable.
   $b now has a reversed array.

Now I want to regroup the elements of the array back into a string, and store that back into a variable:

PS d:\> $c = -join($b)

PS d:\> $c

Edcba

And my string is back to a string again:

PS d:\> $c.GetType()

IsPublic IsSerial Name                             BaseType

——– ——– —-                                     ——–

True     True     String                              System.Object

SS, that is all there is to using Windows PowerShell to reverse strings. Join me tomorrow when I will talk about more cools stuff.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy 

0 comments

Discussion is closed.

Feedback usabilla icon