包含密码的变量的 Powershell 转义 [英] Powershell escape for variables that contain passwords

查看:54
本文介绍了包含密码的变量的 Powershell 转义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我使用了一个包含密码的变量,最近才发现一些密码包含特殊字符.我无法控制密码是什么,所以我必须处理我得到的任何东西.我知道反勾号 '`' 字符是用来转义字符的.这篇文章的全部原因是我发现密码是文本文件,并将找到的密码替换为xxxxxxxxx"模式.

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##!"

因为 $pass 变量包含 '$' 字符,$123asd 被视为没有值的变量

Because the $pass variable contains the '$' character the $123asd is seen as a variable that has no value

$pass

所以你得到的是:

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.

推荐答案

-replace 是正则表达式操作符,$ sigil 确实是正则表达式中的特殊字符.

-replace is a regular expression operator, and the $ sigil is indeed a special character in regex.

您可以使用 [regex]::Escape() 对文字字符串中的所有正则表达式元字符进行转义:

You can escape all regex meta-characters in a literal string with [regex]::Escape():

$output | foreach-object { $_ -replace [regex]::Escape("$pass"), 'xxxxxxxx' }

这篇关于包含密码的变量的 Powershell 转义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆