问题
So I am using a variable that contains a password and just recently found out that some of the passwords are containing special characters. I have no control over what the password is so I have to deal with whatever I am getting. I know the back tick '`' character is what is used to escape characters. The whole reason for this post is that I am finding passwords is text files and replacing the found password with a pattern of 'xxxxxxxxx'.
Currently the code I am using is this:
$pass = "DR$123asd##!"
Because the $pass variable contains the '$' character the $123asd is seen as a variable that has no value
$pass
so all you get is:
DR##!
If I change the pass variable like this
$pass = 'DR$123asd##!'
$pass
DR$123asd##!
Then the '$' character is ignored and the string is complete, but If I run the code:
$output | foreach-object { $_ -replace "$pass", 'xxxxxxxx' }
This is my password DR$123asd##!, It is a great password!
The password doesn't get replaced and I'm, not sure why.
回答1:
-replace
is a regular expression operator, and the $
sigil is indeed a special character in regex.
You can escape all regex meta-characters in a literal string with [regex]::Escape()
:
$output | foreach-object { $_ -replace [regex]::Escape("$pass"), 'xxxxxxxx' }
来源:https://stackoverflow.com/questions/48009027/powershell-escape-for-variables-that-contain-passwords