Search This Blog

Match a string ending with a dollar sign ($) and containing a variable in PowerShell

In my previous post, I can match a string ending with a dollar sign ($) using the single quote with the expression ‘\$$’. Because the single quote protects the PowerShell automatic variable $$ from being evaluated. But it brings up my next question, how about the same expression also includes other variable that should be evaluated. Like this example.

PS C:\Temp> $name = 'smith'
PS C:\Temp>
PS C:\Temp> 'contoso\john.smith$' -match "$name"
True
PS C:\Temp> 'contoso\john.smith$' -match '$name'
False

Obviously, I have to use the double quote to evaluate the variable $name before sending the expression to the regex engine. But I also need the single quote for the variable $$.

PS C:\Temp> 'contoso\john.smith$' -match '$name\$$'
False
PS C:\Temp> 'contoso\john.smith$' -match "$name\$$"
False

Here is my solution - using double quote with both the regex escape character backslash(\) and PowerShell escape character backpack(`).

PS C:\Temp> 'contoso\john.smith$' -match "$name\$`$"
True

Let me explain
  • Use double quote to evaluate the variable $name
  • Use `$ to prevent the automatic variable $$. Using the PowerShell escape character (`) because it’s the PowerShell evaluation, not regex evaluation. So do not use \$ on the second $.
  • After the variable evaluation, the expression becomes smith\$$. This is passed to the regex engine. As expected, this regex matches the string ending with smith$.

No comments:

Post a Comment

Use WinSCP to Transfer Files in vCSA 6.7

This is a quick update on my previous post “ Use WinSCP to Transfer Files in vCSA 6.5 ”. When I try the same SFTP server setting in vCSA 6.7...