How to Limit String Length in PowerShell (With Example)


Often you may want to limit the length of a string to a certain number of characters in PowerShell.

You can use the following syntax to do so:

$new_string = $my_string[0..4] -join ""

This particular example creates a new string named $new_string that limits the length of the string stored in the variable named $my_string to a total of 5 characters.

This syntax works by first using $my_string[0..4] to extract the characters in index positions 0 through 4, i.e. the first five characters of the string.

Then we use the -join operator to join each of these characters together into one string, using nothing as a separator.

This has the effect of limiting the original string to a length of 5.

The following example shows how to use this syntax in practice.

Example: How to Limit String Length in PowerShell

Suppose that we create a string variable in PowerShell named $my_string that contains the following text:

  • “Mavericks”

Now suppose that we would like to create a new variable named $new_string that limits this original string to a total length of 5 characters.

We can use the following syntax to do so:

$my_string = "Mavericks"
$new_string = $my_string[0..4] -join ""

The following screenshot shows how to use this syntax in practice:

PowerShell limit string length

We can see that the new string variable named $new_string contains “Maver”, which represents the first five characters of the original string.

It’s worth noting that if you attempt to limit the string to a length that is longer than the original string, then this syntax will simply return the entire original string.

For example, suppose we attempt to limit the original string to 100 characters:

$my_string = "Mavericks"
$new_string = $my_string[0..100] -join ""

The following screenshot shows how to use this syntax in practice:

We can see that the new string variable named $new_string contains “Mavericks”, which represents the entire original string.

Note: You can find the complete documentation for the -join operator in PowerShell here.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Find Position of Character in String
PowerShell: How to Replace Every Occurrence of String in File
PowerShell: How to Replace Text with Wildcard
PowerShell: How to Replace Special Characters in String

Leave a Reply