PowerShell Basics: Detecting if a String Ends with a Certain Character

Did you know you can detect if a string ends in a specific character, or if it starts in one in PowerShell? This can be doe easily with the use of regular expressions or more simply know as Regex.

Consider the following examples:

'something\' -match '.+?\\$'
#returns true

'something' -match '.+?\\$'
#returns false

'\something' -match '^\\.+?'
#returns true

'something' -match '^\\.+?'
#returns false

In the first two examples, the script checks the string ends to see if it ends in a backslash. In the last two examples, the script check the string to see if it starts with one. The regex pattern being matched for the first two is .+?\$ . What’s that mean? Well, the first part .+? means “any character, and as many of them as it takes to get to the next part of the regex. The second part \\ means “a backslash” (because \ is the escape character, we’re basically escaping the escape character. The last part $ is the signal for the end of the line. Effectively what we have is “anything at all, where the last thing on the line is a backslash” which is exactly what we’re looking for. In the second two examples, I’ve just moved the \\ to the start of the line and started with ^ instead of ending with $ because ^ is the signal for the start of the line.
Now you can do things like this.

$dir = 'c:\temp'
if ($dir -notmatch '.+?\\$')
$dir += '\'
#returns 'c:\temp\'

Here, the script checks to see if the string ‘bears’ ends in a backslash, and if it doesn’t, I’m appending one.

Comments (2)

  1. Zuba Dalama says:

    I find -like operator more readable:

    ‘something\’ -like ‘*\’
    ‘something\’ -like ‘\*’

    (By the way, internally it is converted to regex and then evaluated)

  2. spacenomyous says:

    for your last example, i’m a fan of parsing the chars of a string
    $dir = ‘c:\temp’
    If ($dir[-1] -notmatch ‘\\’)

Skip to main content