我具有以下功能,该功能可隐藏密码中间字符,并使第一个字符和最后一个字符可见
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;用户 ID = UID1;密码= p ************ 3;连接超时= 120
我还有其他采用JSON格式的连接字符串,因此强制转换为sqlbuilder不适用于这种类型的输入
{“身份验证 类型“:” UsernamePassword“,”用户名“:” someID1“,”密码“:” Yu#gh456!ts“,” EncryptConnection“:true}
我能做的一件事就是这样:
$Json = '{"Authentication Kind":"UsernamePassword","Username":"someID1","Password":"Yu#gh456!ts","EncryptConnection":true}'
$Sql = $Json | ConvertFrom-Json
$Sql.Password
使用
$Sql.gettype().name
我得到
PSCustomObject
我想在函数中应用它,以便检查字符串输入是否为pscustomobject类型,以便不将其强制转换为sqlbuilder
伪代码 :
function Hide-ConnectionStringPassword {
if ($input.gettype().name -ne 'PSCustomObject')
{
param(
[parameter(Mandatory,ValueFromPipeline)]
[System.Data.SqlClient.SqlConnectionStringBuilder]$ConnectionString
)}
else
{
param(
[parameter(Mandatory,ValueFromPipeline)]
$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
}
答案 0 :(得分:1)
您只需删除该参数中的强制输入即可。然后将if-else
逻辑移到脚本Process {}
或Begin {}
脚本块中。
function Hide-ConnectionStringPassword {
param(
[parameter(Mandatory,ValueFromPipeline)]
$ConnectionString
)
if ($ConnectionString.GetType().Name -ne "PSCustomObject") {
$ConnectionString = $ConnectionString -as [System.Data.SqlClient.SqlConnectionStringBuilder]
}
[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
}