Use .NET Framework Classes to Work with Strings in Windows PowerShell

Use .NET Framework Classes to Work with Strings in Windows PowerShell

  • Comments 4
  • Likes

 

Summary: Learn how to use .NET Framework classes to work with strings in Windows PowerShell in this Scripting Guys how-to post.

 

Hey, Scripting Guy! QuestionHey, Scripting Guy! I have been writing VBScript code for years. One thing I really liked about VBScript was the large number of functions that manipulated strings. I know Microsoft seems to love XML, but there is a lot of overhead associated with XML, and very often, I need to parse and manipulate strings. When I look at the Windows PowerShell cmdlets, I do not see very many cmdlets that would allow me to manipulate text.

-- BW

 

Hey, Scripting Guy! AnswerHello BW, Microsoft Scripting Guy Ed Wilson here. When I was a student at the university, I majored in music for a while. One of my favorite classes was a music theory class that focused on string instruments. It was a string theory class. Today, I will examine string theory as it applies to Windows PowerShell. In continuing my discussion of the .NET Framework as it applies to Windows PowerShell, I will examine the System.String .NET Framework class.

Strings are letters, words, and numbers that function like letters and words. The GetType method can be used to determine what kind of object one is working with. This is shown here.

PS C:\> ("this is a string").GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     String                                   System.Object


PS C:\>

As seen above, "this is a string" is an instance of a string object. The .NET Framework class string, is located in the System .NET Framework namespace. Therefore, I will frequently refer it to it as the System.String class because it helps me remember where in the labyrinthine .NET Framework hierarchy the String class resides. Knowing where the class resides is useful when I have to look up information on MSDN, but to create some classes I have to specify both the namespace and the class name.

If the string "this is a string" is an instance of the System.String class, what does that really mean? It means that the class contains methods and properties. The methods do things and are like verbs, whereas the properties describe things and are like adjectives. To find the members (methods and properties) of the System.String class, I can use the Get-Member Windows PowerShell cmdlet. To do this, I first open Windows PowerShell by clicking Start \ Programs \ Accessories \ Windows PowerShell \ Windows PowerShell. If you are tired of meandering through five levels of nested menus to start Windows PowerShell, you may want to create a desktop shortcut to Windows PowerShell. The Scripting Wife talks about this technique. The technique of piping a string to the Get-Member cmdlet is illustrated here. The PS C:\> is not part of the command, but is the Windows PowerShell prompt.

PS C:\> "this is a string" | Get-Member

After the command is typed, and the enter key pressed to submit the command to Windows PowerShell for interpretation, the output seen in the following figure appears.

 

There are many ways to call a method on an instance of a class such as the System.String class seen here. In every example, a dotted notation is used immediately after the class instance that is followed by the method name. Several different ways of calling the toupper method are illustrated here.

PS C:\> ("this is A string").toupper()
THIS IS A STRING
PS C:\> "this is A string".toupper()
THIS IS A STRING
PS C:\> $a = "this is A string"
PS C:\> $a.ToUpper()
THIS IS A STRING
PS C:\> $b = New-Object system.string("this is A string")
PS C:\> $b.ToUpper()
THIS IS A STRING
PS C:\> [string]"this is A string".toupper()
THIS IS A STRING
PS C:\> ([string]"this is A string").toupper()
THIS IS A STRING
PS C:\> [string]("this is A string").toupper()
THIS IS A STRING
PS C:\>

The tolower method works exactly like the toupper method. Whereas the toupper method will take a string and convert all the letters in the string to uppercase (hence the name toupper) the tolower method performs the opposite action. It converts a string to all lowercase characters. In the following example a mixed case string is converted to all uppercase letters and stored in the $a variable. The contents of the $a variable are then displayed on the Windows PowerShell console line. The tolower method is then called to convert the uppercase letters stored in the $a variable to lowercase. The output of the tolower method call is not stored (that is the results are not stored in a variable, they are only displayed on the Windows PowerShell console line). The commands and their associated output are shown here. 

PS C:\> $a = [string]("this is A string").toupper()

PS C:\> $a

THIS IS A STRING

PS C:\> $a.ToLower()

this is a string

PS C:\>

The toupper or the tolower methods are useful for evaluating user input. In the example that follows, the Read-Host Windows PowerShell cmdlet asks for input from the user. If the user types yes, the code continues. Refer to this code for the details.

PS C:\> $rtn = Read-Host "Do you wish to continue? yes / no"

Do you wish to continue? yes / no: yes

PS C:\> if($rtn.ToUpper() -eq "YES") {"continue"} ELSE { "don't continue" }

continue

If the user can be counted upon to type exactly what the prompt expects, then everything will work perfectly. However, this is an unlikely expectation. In the example that follows, the same prompt is displayed by using the Read-Host cmdlet. Instead of typing yes the user types Yes, I would like to continue and the $rtn.ToUpper code fails. The contains method returns a Boolean value if a match in a string is detected. Unfortunately, it is case-sensitive, and because the user typed Yes instead of yes, the contains method fails also. What is needed is the ability to combine the tolower method and the contains method. The last line of the following code achieves that.

PS C:\> $rtn = Read-Host "Do you wish to continue? yes / no"

Do you wish to continue? yes / no: Yes  I would like to continue.

PS C:\> if($rtn.ToUpper() -eq "yes") { "continue" } ELSE { "don't continue" }

don't continue

PS C:\> if($rtn.contains("yes")) { "continue" } ELSE { "don't continue" }

don't continue

PS C:\> if($rtn.tolower().contains("yes")) { "continue" } ELSE { "don't continue" }

continue

PS C:\>

A common problem arising from working with strings is additional spaces. This can cause problems with reporting if the information writes to a database because it can cause equivalent records to report as separate entries. Additional spaces can also cause matches to fail. Luckily, several methods from the System.String .NET Framework class resolve the problem of additional spaces. The methods are TrimStart, TrimEnd, and Trim. I will examine using the TrimStart method first. In the example that follows, a string that contains both leading and trailing spaces is assigned to the $a variable. The TrimStart method is used to remove leading spaces and the result is stored in the $b variable. To show where spaces remain, the Replace method replaces spaces with a period. This shows in the following output.

PS C:\> $a = " this is a string  "

PS C:\> $b = $a.TrimStart()

PS C:\> $b.Replace(" ",".")

this.is.a.string..

PS C:\>

The TrimEnd method works just as the TrimStart method does, except that it removes spaces from the end of a string. The string with spaces is assigned to the $a variable. The TrimEnd method removes spaces from the end of the string and assigns the result to the $b variable. Finally, the Replace method replaces spaces with periods  so that the spaces are more clearly visualized. The output that follows shows this procedure.

PS C:\> $a = " this is a string  "

PS C:\> $b = $a.TrimEnd()

PS C:\> $b.Replace(" ",".")

.this.is.a.string

PS C:\>

The last trim method I want to discuss is the one that I use most frequently. It is the Trim method. What I like about the Trim method is that it removes leading spaces in addition to trailing spaces. To achieve the same effect, if one did not know about the Trim method, would involve calling both the TrimStart and the TrimEnd methods as shown here.

PS C:\> $a = " this is a string  "

PS C:\> $b = $a.TrimEnd().TrimStart()

PS C:\> $b.Replace(" ",".")

this.is.a.string

PS C:\>

In fact, the Trim method does the same. It removes leading spaces just as the TrimStart method does, and it removes trailing spaces as the TrimEnd method does. The following code shows this concept.

PS C:\> $a = " this is a string  "

PS C:\> $b = $a.Trim()

PS C:\> $b.Replace(" ",".")

this.is.a.string

PS C:\>

BW, that is all there is to using .NET Framework classes to work with strings. My review of the .NET Framework for Windows PowerShell week will continue tomorrow when I will talk about more how to work with the .NET Framework classes.

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

 

Ed Wilson, Microsoft Scripting Guy

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment
  • <p>Yep this is one of the great things about Powershell. But as long as you know the namespace, it should in principle be possible to use any .Net class shouldn&#39;t it?</p>

  • <p>Thanks, great work, I&#39;ve followed you guy&#39;s on and off for several years. &nbsp;Thanks, Ken</p>

  • <p>Some of the .NET Framework classes have special requirements. For example, the System.Windows.Forms.Clipboard class has the requirement that it can only be used in threads that are set to single thread apartment mode. The Windows PowerShell ISE automatically starts in STA mode. The Windows PowerShell console can be launched in STA mode by using the following command powershell -sta keep in mind that Windows PowerShell 2.0 is required for STA mode. There may be other classes that will need their assembly loaded, and maybe other requirements. MSDN is the best source of this type of information. But, Windows PowerShell 2.0 is quite powerful in this regard. </p>

  • <p>Hi Scripting Guy, &nbsp;How would I handle an error that results from calling a method? &nbsp;-EA doesn&#39;t seem to handle this.</p>