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? Thomas Rayner previously shared on CANITPRO.NET how this can be easily done by using regular expressions or more simply know as Regex.
Consider the following examples:
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 “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:
Here, the script checks to see if the string ‘bears’ ends in a backslash, and if it doesn’t, I’m appending one.
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 “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 += '\'
}
$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.