Search This Blog

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

I want to match a string ending with a dollar sign ($) (e.g. ‘contoso\john.smith$’) in PowerShell. Using the regular expression (regex) should be simple, like \$$.

However, I run into some problem in PowerShell. I posted my question in Reddit for help. With the comments from the community, I think I finally understand how to handle this issue. This blog post is to summarize my understanding.
  • -match operator uses the regular expression syntax.
  • The scape character in regex is the backslash(\). Normally the regular PowerShell escape character, the backtick(`), should not use in the regex expression. See my next post on using both scape characters (\ and `) in one expression.
  • To match a string ending with a dollar sign ($), the regex should be \$$. The first $ is for the literal $, so it is escaped by \. The second $ is an anchor which matches the end of a string, so it is not escaped by \.
  • However $$ is an automatic variable in PowerShell.
  • When the expression(\$$) is doubled-quoted, PowerShell evaluates the variable $$ first before sending to the regex engine. “\$$” becomes “\{value of $$}” when being parsed by the regex engine. So it returns False.
PS C:\Temp> 'contoso\john.smith$' -match "\$$"
False
  • When the expression(\$$) is single-quoted, PowerShell does not evaluate any variable. The expression \$$ is parsed by the regex engine. So it returns True.
PS C:\Temp> 'contoso\john.smith$' -match '\$$'
True

In the case, I can match a string ending with $ by using the single quote with the expression '\$$'. However, this will not work if the expression includes other variable that should be evaluated. I will post my solution in the next post.

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...