如何用*替换字符串中的中间字符? [英] How to replace middle chars with * in a string?
本文介绍了如何用*替换字符串中的中间字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下内容
$builder = [System.Data.SqlClient.SqlConnectionStringBuilder]::New('Connection Timeout=120;User Id=UID1;Data Source=datasource.com;Password=password12!553;')
$builder
这将按原样打印出连接字符串.
This will print out the connection string as is.
我想打印出带有密码的连接字符串,只显示第一个和最后一个字符,中间的其余字符为 *
i want to print out the connection string with password showing only the 1st and last chars, and rest of chars in middle as *
Connection Timeout=120;User Id=UID1;Data Source=datasource.com;Password=p************3;
我怎样才能动态完成(即知道密码值的长度,然后用 * 替换中间字符)?
how can i accomplish that dynamically (i.e. knowing the length of the password value and then replacing the middle chars with *)?
pseudocode: $builder.Password -replace($_ middle_chars, "*")
推荐答案
function Hide-ConnectionStringPassword {
param(
[parameter(Mandatory,ValueFromPipeline)]
[System.Data.SqlClient.SqlConnectionStringBuilder]$ConnectionString
)
[string]$FistChar = $ConnectionString.Password[0]
[string]$LastChar = $ConnectionString.Password[($ConnectionString.Password.Length - 1)]
[string]$Stars = '*' * ($ConnectionString.Password.Length - 2)
$ConnectionString.Password = $FistChar + $Stars + $LastChar
return $ConnectionString.ConnectionString
}
Hide-ConnectionStringPassword 'Connection Timeout=120;User Id=UID1;Data Source=datasource.com;Password=password12!553;'
输出:
Data Source=datasource.com;User ID=UID1;Password=p************3;Connect Timeout=120
这篇关于如何用*替换字符串中的中间字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文