The processing of strings is one of the most common operations in scripting languages. Traditional tools such as batch files or VBScript can only cope with these tasks in a rather awkward way. In contrast, PowerShell offers the complete arsenal of string manipulation functions that you might know from PHP or JavaScript.

It is important to understand that strings in PowerShell are always objects, whether you are dealing with literal strings or variables. Consequently, the methods of string objects provide most of the functions you need. As usual, you can display them with the Get-Member cmdlet.

"Hello world" | Get-Member

The result list is impressive:

Clone CompareTo Contains CopyTo EndsWith
Equals GetEnumerator GetHashCode GetType GetTypeCode
IndexOf IndexOfAny Insert IsNormalized LastIndexOf
LastIndexOfAny Normalize PadLeft PadRight Remove
Replace Split StartsWith Substring ToBoolean
ToByte ToChar ToCharArray ToDateTime ToDecimal
ToDouble ToInt16 ToInt32 ToInt64 ToLower
ToLowerInvariant ToSByte ToSingle ToString ToType
ToUInt16 ToUInt32 ToUInt64 ToUpper ToUpperInvariant
Trim TrimEnd TrimStart

Concatenating strings

However, some tasks require the use of operators. For example, PowerShell doesn’t have a concat function. Instead, you can just concatenate two or more strings with the plus operator:

$h = "Hello" 
$w = "world"
$h + " " + $w

Alternatively, you can expand the two strings within double quotes:

"$h $w"

In the example, the space guarantees that the two words don’t stick together. However, you could insert any other delimiter.

Concatenating strings. in PowerShell

Concatenating strings in PowerShell

This method is also suitable for concatenating the elements of a string array:

$st = @("Say hello", " world")
"$st"

PowerShell automatically inserts a space here between the linked array elements.

Another option for concatenating strings is the join operator. Its usage is perhaps a bit counterintuitive. Normally, you place the operator in front of the string unless you want to separate the strings with a delimiter after the merge:

-join($h,$w)

If you don’t like the result “Helloworld” in the example and you want to add a space between the two words, you have to call -join this way:

$h,$w -join " "

Splitting strings

For the opposite task (that is, for splitting strings), you can use either the split method or the split operator. The former is simpler and only allows for use of explicit delimiters; the operator, on the other hand, supports regular expressions.

In the following example, the string is split at the double “ll” and at the space. The delimiter itself falls by the wayside:

("Hello world").split("ll"" ")

You can specify the maximum number of substrings in which the string is split. PowerShell will then produce an array with the corresponding number of elements:

("Hello world").split("ll"" ", 2)

The result array in the above example has two elements.

Extracting substrings

The method Substring has a similar purpose because it can extract a part of the string. However, instead of using delimiters, you have to specify the position and length of the string that you want to extract:

("Hello world").Substring(2,5)

This command results in “llo w”, which corresponds to the substring with a length of five characters that begins at the third character (counting begins at 0!).

The counterpart method to Substring is Remove. It deletes the specified range from the string:

("Hello world").Remove(2,3)

In this example, “llo” is removed from “Hello world.”

To eliminate leading or trailing spaces, you can use TrimStart, TrimEnd, or Trim.

Searching and replacing characters

PowerShell knows a variety of techniques to find and replace substrings. For the more demanding tasks, regular expressions are available, which can be applied with the -match or -replace operators.

In addition, the string object offers several methods for this task. Of course, each of these methods has its specific purpose. Replace is the simplest of these methods and doesn’t support regular expressions.

("Hello World").Replace("Hello","New")

A counterpart to the -match operator doesn’t exist. However, PowerShell supports several methods that specialize on a particular search type. For instance, StartsWith and EndsWith determine whether a string begins or ends with a certain character or string, respectively. Likewise, Contains tells you if a string contains a certain substring:

("Hello world").Contains("ll")

The above command results in True. To calculate the position of a character or substring in the string, IndexOf is at your disposal:

("Hello world").IndexOf("ll")

Don’t forget that counting starts at 0!

Searching and replacing characters in PowerShell

Searching and replacing characters in PowerShell

Comparing strings

In general, you can work with the same comparison operators as for numerical values to determine differences between strings. Primarily, this includes -eq and -ne, as well as -like, which supports wildcards.

String objects also offer methods for this purpose. If the first string is “bigger” than the second string (that is, if it comes first in the sort order), the cmdlet returns 1; if the first string is smaller, the result is ‑1.

("Hello world").CompareTo("Hello" + " " + "world")

In the above example, CompareTo returns 0 because the strings are identical. In contrast, the comparable call with Equals returns True:

("Hello world").Equals("Hello" + " " + "world")
avataravataravatar
20 Comments
  1. Christian Sapp 7 years ago

    Great examples, I’m trying to find a way to perform string aggregation similar to the way wm_concat used to work in oracle sql.  Wondering if you have any ideas.

    Example:

    csv input file containing the following Input:

    empid,fname,lname,access_priv

    123456,jane,doe,bldg1

    123457,joe,smith,bldg1

    123456,jane,doe,bldg2

    123456,jane,doe,bldg3

    123457,joe,smith,bldg2

    Desired output:

    123456,jane,doe,bldg1,bldg2,bldg3

    1232457,joe,smith,bldg1,bldg2

     

    any thoughts would be greatly appreciated.

     

    Thanks

    Christian

    • vigou 6 years ago

      Hi Christian,

      I have the same problem.

      Do you have find a powershell solution.

      Can you send me a sampe script.

      Thanks

  2. Dzung Nguyen 7 years ago

    Hi Wolfgang,

    I want to replace multiple strings in a text log file. The string begin with X-ARR.., the string has 50 characters including letter, number and hyphen. I would like to replace/remove it. How would I do it with the string?

    Thanks advance for your help.

    Nguyen

  3. hari 7 years ago

    HI Wolfgang,

     

    I need to replace only full string matches : I have a hashtable with key value pairs like

    “Id”,”Name”

    “Name”, “Full Name”

    “UserId”,”ADId”

    etc .,

    But when I try to use replace function in a text

    Userid is renamed as UserName

  4. Kevin 6 years ago

    I am trying to identify users with two legal last names and replace the space with a “-“. If they only have a single last name it will just proceed with the script.

    if ($line.lastname).Contains(” “) {

    $LastName = ($line.lastname).replace(” “,”-“)

    } else { $LastName = ($line.lastname)

    • Carey 6 years ago

      Kevin…did you get an answer yet?  If not, here is what worked for me:

      if ( ($line.lastname).Contains(” “) -eq $true) {

      $LastName = ($line.lastname).replace(” “,”-“)

      } else { $LastName = ($line.lastname) }

  5. Paulus 6 years ago

    Gutentag Wolfgang,

    Being a Powershell newbee, I tried out your example:

    (“Hello world”).split(“ll”” “)

    However, this is giving the same result as with using a single l

    (“Hello world”).split(“l”” “)

    That is: even when specifying the double ll as delimiter, a split is executed for ‘world’ all the same!?

    I would have expected that only the double occurrence of ll would be accepted as delimiter…

    He

    o
    wor
    d

    • Paulus, the output is the same because the split method (unlike the -split operator) uses a char array (an array of characters) to split the string with each character in the array. Thus, if you repeat a character in your separator, it has no effect.

      If you understand this, you got the point:

      PS C:\> ("Hello world").split("lHlll")
      
      e
      
      o wor
      
      d

      If you want to split with a string instead of a character, you can use the -split operator:

      PS C:\> "Hello world" -split "ll"
      
      He
      
      o world

      Just take into the account that the -split operator uses regex in the delimiter.

  6. @Wolfgang,

    You switched the method and the operator words for the split’s explanation.

    The split method support regular expressions.

    https://msdn.microsoft.com/en-us/library/system.string.split(v=vs.110).aspx

    The split operator allows for use of explicit delimiters.

    https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.core/about/about_split

    Anyway, very good post Wolfgang!

    Thank you!

  7. Sanjeev 6 years ago

    (“Hello world”).Remove(2,3) removes ‘llo’ and not ‘ell’ as mentioned in the article.
    Output: He world

    Thanks.

  8. aby said 5 years ago

    Hi

    Need help with the following:

    PS C:\share> Get-WmiObject win32_networkadapterconfiguration -filter “Description = ‘Array Networks VPN Adapter'” | Format-List -Property IPAddress -outvariable variable

    IPAddress : {10.1.200.150}

    PS C:\share>

    How to take the output on a variable but with only the IP…..? rather then IPAddress : {10.1.200.150} I want only IPAddress : 10.1.200.150

    • You can use regex with the -match operator:

      $variable -match "IPAddress : {(.+)}"
      'IPAddress : ' + $matches[1]

      Note that this assumes that the IP is between curly brackets. If IPv6 is enabled on the computer, this will also include the IPv6 address.

  9. @aby,

    If you just want the IP Address, try this:

    Get-WmiObject win32_networkadapterconfiguration -Filter "Description = '%adapter description%'" | Select-Object -ExpandProperty ipaddress

  10. CaptainTact (Rank 1) 4 years ago

    Hey Wolfgang!  Great article.  One question though.

    I did a search for all mail-enabled security groups in our Org that we are using as ACLs for Shared Mailboxes.  Those group Display Names all end in "-Full" so it's a pretty easy query.  

    $Full = Get-DistributionGroup -ResultSize Unlimited | Where {$_.Alias -Like "*Full"} | Select Alias

    Once I have the alias of those groups, I want to strip off the "Full" portion so that I wind up with the alias of the mailbox it is connected to.  I.E., ACL alias is "TestMailboxFull" and is used to regulate access to the shared mailbox with an alias of "TestMailbox".

    In order to do that, I ran this command:

    $MbxAliases = $Full.Replace("Full","")

    However, when I run that, I get the following error:

    Method invocation failed because [Selected.Microsoft.Exchange.Data.Directory.Management.DistributionGroup] does not
    contain a method named 'Replace'.
    At line:1 char:1
    + $Aliases = $Aliases.Replace("Full","")
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidOperation: (Replace:String) [], RuntimeException
        + FullyQualifiedErrorId : MethodNotFound

    Any ideas as to what I am doing wrong?

    • Hi,
      The command 'Get-DistributionGroup' retrieves the Distribution Groups and outputs an array of Distribution Group objects.
      Every object type supports a certain list of operations.
      Some of the operations supported by string type are explained in the above article.
      So as a solution to perform string operations we can either convert the object type to string or create a new string object from some of the properties of the distribution Group object.

      Going with the second solution, Final flow would look something like this.

      $FullDGs = Get-DistributionGroup -ResultSize Unlimited | Where {$_.Alias -Like "*Full"} | Select Alias
      Foreach($dg in $FullDGs)
      {
      $FullDGstr = $dg.displayname
      $MbxAlias = $FullDGstr.Replace("Full","")
      $MbxAliases += $MbxAlias
      }

      *Note I do not have the environment to test right now. You may have to tweak a bit.
      *With piping and filters your requirement can be fulfilled in one line command as well. However, I would not recommend going for it at this stage.

  11. Anita 3 years ago

    Hi

    Need help with the following:

    I am running below command using shell script to get active session count from skype server.

    Get-CsWindowsService -Name RTCMEDIARELAY  | Select-Object -ExpandProperty ActivityLevel

    Result: Active Sessions=100

    I  just wanted to take value 100 from output. and place it in txt file. Please help me how we can do this.

  12. Panny 2 years ago

    Thanks for very good explanation with example code. Help me put my script together quickly.

Leave a reply

Your email address will not be published.

*

© 4sysops 2006 - 2023

CONTACT US

Please ask IT administration questions in the forums. Any other messages are welcome.

Sending

Log in with your credentials

or    

Forgot your details?

Create Account