PowerShell: How to Trim String to Specific Length


Often you may want to trim a string in PowerShell to a specific length that it should not exceed.

You can use the following basic syntax to do so:

$my_string.Substring(0, [System.Math]::Min(12, $my_string.Length))

This particular example will trim the string stored in the $my_string variable so that it does not exceed a length of 12 characters.

If the string is already less than 12 characters then the entire original string will be kept.

Here is how this syntax works:

  • The first argument of the Substring() method specifies the starting index position to return.
  • The second argument of the Substring() method specifies the length of characters to return after the starting position.
  • By using [System.Math]::Min(12, $my_string.Length) we specify that the length argument should be the minimum of either 12 or simply the length of the entire string.

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

Example: How to Trim String to Specific Length in PowerShell

Suppose that we have the following string in PowerShell:

  • A003EmployeeGreg

Suppose that we would like to trim this string to have a max length of 12 characters.

We can use the following syntax to do so:

$my_string = "A003EmployeeGreg"
$my_string.Substring(0, [System.Math]::Min(12, $my_string.Length))

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

PowerShell trim string to length

This returns the following string:

  • A003Employee

This string has a length of 12, which is the max length that we specified.

Suppose instead that we had the following string in PowerShell:

  • A003Emp

Suppose that we attempt to trim this string to have a max length of 12 characters.

$my_string = "A003Emp"
$my_string.Substring(0, [System.Math]::Min(12, $my_string.Length))

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

This returns the following string:

  • A003Emp

Since the string already had a length less than 12 characters, the string is not trimmed at all.

Related Tutorials

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

PowerShell: How to Trim Leading Spaces from String
PowerShell: How to Extract Text Between Two Strings
PowerShell: How to Extract Only Numbers from String

Leave a Reply