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).
Consider the following examples:
'something\' -match '\\$' #returns true 'something' -match '\\$' #returns false '\something' -match '^\\' #returns true 'something' -match '^\\' #returns false
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\'
Source: https://habr.com/ru/post/441428/
All Articles