Powershell – Substring() from the end of the string

Definition: Returns a specified number of characters from the right side of a string.


You can use the Substring() method to retrieve a specified number of characters from the beginning of a string. That’s great, but how do you return a specified number of characters from the end of a string?

Here’s one sneaky way to do that. Use the Substring() method, specifying the following two parameters:

  • The starting position, which should be the length of the string minus the number of characters you’re after. If you want the last 4 characters in the string then use the length minus 4.
  • The number of characters you want returned.

For example, these two commands assign a value to the variable $a, then use the Substring() method to retrieve the last 9 characters in the string:

$a = $a.substring($a.length - 9, 9)

When you run this command and then echo back the value of $a you should get the following: