如何用字符串中的*替换中间字符?

时间:2019-07-09 00:51:49

标签: powershell

我有以下

$builder = [System.Data.SqlClient.SqlConnectionStringBuilder]::New('Connection Timeout=120;User Id=UID1;Data Source=datasource.com;Password=password12!553;')

$builder

这将按原样打印出连接字符串。

我想打印出带有密码的连接字符串,该密码仅显示第一个和最后一个字符,中间的其余字符显示为*

Connection Timeout=120;User Id=UID1;Data Source=datasource.com;Password=p************3; 

我该如何动态地做到这一点(即知道密码值的长度,然后用*替换中间的字符)?

pseudocode: $builder.Password -replace($_ middle_chars, "*") 

1 个答案:

答案 0 :(得分:2)

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