Reputation: 3521
I have the following function that hides a password middle chars and leaves 1st and last char visible
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
}
Usage:
Hide-ConnectionStringPassword 'Connection Timeout=120;User Id=UID1;Data Source=datasource.com;Password=password12!553;'
output:
Data Source=datasource.com;User ID=UID1;Password=p************3;Connect Timeout=120
I have other connection strings that are JSON formatted, so the casting to sqlbuilder will not work on this type of input
{"Authentication Kind":"UsernamePassword","Username":"someID1","Password":"Yu#gh456!ts","EncryptConnection":true}
One thing i could do is something like this:
$Json = '{"Authentication Kind":"UsernamePassword","Username":"someID1","Password":"Yu#gh456!ts","EncryptConnection":true}'
$Sql = $Json | ConvertFrom-Json
$Sql.Password
with
$Sql.gettype().name
i get
PSCustomObject
i would like to apply that in the function such that it checks string input is type pscustomobject so that it doesnt cast it as sqlbuilder
pseudocode:
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
}
Upvotes: 0
Views: 40
Reputation: 25001
You could just remove the hard typing in the parameter. Then move the if-else
logic to the script Process {}
or Begin {}
script blocks.
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
}
Upvotes: 1