fredag 10 juni 2011

PowerShell: Useful info about strings

Strings in PowerShell are instances of System.String (.NET). This enables us to use all functions and properties we are used to from C#/VB.NET: PS> $mystring = "Hello bob"
PS> $parts = $mystring.split(" ")
PS> [System.String]::Format("{0} {1}", $parts[0], $parts[1])
Hello bob

There are also a few string-specific operators that can be used: -split, -join, -f (scroll down to 'Special operators')

PS> write-host $("Hello {0}" -f "bob")
Hello bob
Notice the use of $(...) here, it is a sub-expression that is required in this case to make sure that the expression is executed first and sent to write-host as a single argument. See about_Operators (scroll down to 'Special operators') for more information.

Furthermore, there are special cases such as -like, -contains and -match in comparison operators that makes our lives even easier.

Concatenating strings is done in the usual way, with the plus-sign. Using variables inside a string can be done when using double-qoutes. Escaping on the other hand is by using the backtick, not backslash as most of us are used to:

PS> $myname = "bob"
PS> $mystring = "Hello " + "$myname `"The drooling monkey`""
Hello bob "The drooling monkey"

And last but not least

A few wise words about the cmdlet Select-String and a "general rule" of PowerShell:
If you're parsing a string in Windows PowerShell, you're doing something wrong
Don Jones Read the article from Don Jones here

Inga kommentarer:

Skicka en kommentar