PowerShell: How to Get Last Character of String


You can use the following methods in PowerShell to get the last character of a string:

Method 1: Get Last Character of String

$my_string.Remove(0, ($my_string.Length - 1))

This particular example gets the last character in the string variable named $my_string.

Method 2: Get Last N Characters of String

$my_string.Remove(0, ($my_string.Length - 3))

This particular example gets the last 3 characters in the string variable named $my_string.

Method 3: Get Last N Characters of Each Line in File

foreach ($Line in Get-Content $my_file) {
    $Line.Remove(0, ($Line.Length - 4))
}

This particular example gets the last 4 characters from each line in the file path specified in the variable named $my_file.

The following examples show how to use each method in practice.

Example 1: Get Last Character of String in PowerShell

We can use the following syntax to get the last character of a string variable in PowerShell:

$my_string = "hello everybody"
$my_string.Remove(0, ($my_string.Length - 1)) 

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

PowerShell get last character in string

We define the string variable to be “hello everybody” and this syntax returned “y” which represents the last character in the string.

Example 2: Get Last N Characters of String in PowerShell

We can use the following syntax to get the last three characters of a string variable in PowerShell:

$my_string = "hello everybody"
$my_string.Remove(0, ($my_string.Length - 3)) 

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

PowerShell get last n characters of string

We define the string variable to be “hello everybody” and this syntax returned “ody” which represents the last three characters in the string.

Note: Replace 3 with n to instead extract the last n characters from the string.

Example 3: Get Last N Characters of Each Line in File in PowerShell

We can use the following syntax to get the last four characters of each line in a specific text file in PowerShell:

$my_file = "c:\users\bobbi\cities.txt"

foreach ($Line in Get-Content $my_file) {
    $Line.Remove(0, ($Line.Length - 4))
}

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

PowerShell get last characters of each line in PowerShell

The text file that we specified contains a list of city names.

Notice that our script returned the last four characters from each city name in the text file.

Related Tutorials

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

PowerShell: How to Get Last Item in Array
PowerShell: How to List Files in Directory by Date
PowerShell: How to List All Files in Directory to Text File

Leave a Reply