PowerShell: How to Check if String Ends with Specific Value


You can use the EndsWith() method in PowerShell to check if a string ends with a specific value.

There are two common ways to use this method in practice:

Method 1: Check if String Ends with Value (Return True or False)

$employee_ID.EndsWith("C")

This particular example will check if the string stored in the variable named employee_ID ends with the character “C” and return either True or False.

Method 2: Check if String Ends with Value (Return Custom Output)

if($employee_ID.EndsWith("C"){
    Write-Host("String ends with C")
}else {
    Write-Host("String does not end with C")
}

This particular example will check if the string stored in the variable named employee_ID ends with the character “C” and return custom output as a result.

The following examples show how to use each of these methods in practice.

Example 1: Check if String Ends with Value (Return True or False)

Suppose that we define a variable named employee_ID with the following text:

  • Manager005BC

We can use the following syntax with the EndsWith() method to check if this string ends with the character “C” and return True or False as a result:

$employee_ID = "Manager005BC"
$employee_ID.EndsWith("C")

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

PowerShell check if string ends with value

This returns True because the employee_ID variable does indeed end with “C” as the last character.

Example 2: Check if String Ends with Value (Return Custom Output)

Once again, suppose that we define a variable named employee_ID with the following text:

  • Manager005BC

We can use the following syntax with the EndsWith() method to check if this string ends with the character “C” and use an if else statement to return custom output as a result:

$employee_ID = "Manager005BC"

if($employee_ID.EndsWith("C"){
    Write-Host("String ends with C")
}else {
    Write-Host("String does not end with C")
}

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

PowerShell check if string ends with value in if else statement

This returns the output String ends with C because the employee_ID variable does indeed end with “C” as the last character.

Related Tutorials

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

PowerShell: How to Replace Multiple Strings in File
PowerShell: How to Check if String Exists in List of Strings
PowerShell: How to Replace Special Characters in String
PowerShell: How to Replace Text in String

Leave a Reply