📜 ⬆️ ⬇️

PowerShell Basics: Defining the End of a Line with a Specific Character

Did you know that you can determine if a string ends with a specific character or starts with it in PowerShell? Thomas Rayner previously shared on CANITPRO.NET, as it is easy to do with regular expressions (or, more simply, Regex).




Thanks for the translation to our MSP, Lev Bulanov .

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 whether the string ends with a backslash. In the last two examples, the script checks the string to determine if it begins with a slash.
')

The regular expression pattern for the first two looks like this "\\ $". What does it mean? Well, the first part of \\ means "backslash" (because \ is an escape character, and we basically escape the escape character. The last part of $ is the end of line signal. In fact, we have "nothing at all where the last what stands on the line is backslash, ”and this is exactly what we are looking for.


In the following two examples, I simply moved \\ to the beginning of the line and started with ^, not $, because ^ is the signal for the beginning of the line.


Now you can do things like:


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

Here the script checks if the string 'bears' ends with a backslash, and if not, I will add it.

Source: https://habr.com/ru/post/441428/


All Articles