Powershell escape for variables that contain passwords

你说的曾经没有我的故事 提交于 2021-02-05 08:19:26

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!