Home » How to Get the Last Character of String in PowerShell

How to Get the Last Character of String in PowerShell

You can use multiple ways to get the last character of a string in PowerShell.

The following methods show how you can do it with syntax.

Method 1: Using index

$myString = "ActiveDirectoryTools"
$lastChar = $myString[-1]
Write-Output "Last Character is: $lastChar"

This example will output the last character of a string.

Method 2: Using the Substring method

$myString = "ActiveDirectoryTools"
$lastChar = $myString.Substring($myString.Length -1)
Write-Output "Last Character is: $lastChar"

This example will output the last character of a string using the Substring() method of a string.

The following examples show how you can use these methods.

Get the Last Character of the String Using the Index in PowerShell

You can index in PowerShell to get the last character of a string.

$myString = "ActiveDirectoryTools"
$lastChar = $myString[-1]
Write-Output "Last Character is: $lastChar"

Output:

PowerShell get last character of a string
PowerShell get last character of a string

In this PowerShell script, the $myString variable stores the string data “ActiveDirectoryTools“. We then use the index over the string variable like $myString[-1] to get the last character of a string.

Finally, the last character of a string is output to the console using the Write-Output cmdlet.

Get the Last Character of a String Using the Substring method

You can use the Substring() method of a string to get the last character of a string.

$myString = "ActiveDirectoryTools"
$lastChar = $myString.Substring($myString.Length -1)
Write-Output "Last Character is: $lastChar"

Output:

PowerShell get last character of a string using substring
PowerShell get the last character of a string using a Substring() method

In this script, the $myString variable stores the string data “ActiveDirectoryTools“. We then use the Substring() method over the $myString variable to get the last character of a string.

Finally, the last character of a string is output to the console using the Write-Output cmdlet.

Conclusion

I hope the above article on getting the last character of a string in PowerShell is helpful to you.

You can find more topics about Active Directory tools and PowerShell basics on the ActiveDirectoryTools home page.