function ConvertFrom-ConfigurationDataSecretValue { [CmdletBinding()] Param( [Parameter(Mandatory=$true)] [AllowNull()] $Secret, [Parameter(Mandatory=$true)] [ValidateSet("credential", "securestring", "string")] [string] $ExpectedType, [Parameter(Mandatory=$false)] [string] $Name = "", [Parameter(Mandatory=$false)] [string] $UserName = "" ) if($null -eq $Secret){ throw "Secret [$Name] was not found." } if($ExpectedType -eq "credential"){ if($Secret -is [System.Management.Automation.PSCredential]){ return $Secret } if($Secret -is [System.Collections.IDictionary]){ if([string]::IsNullOrWhiteSpace($UserName) -and $Secret.Contains("UserName")){ $UserName = [string]$Secret["UserName"] } if($Secret.Contains("Password")){ return ConvertTo-ConfigurationDataCredential -UserName $UserName -Password $Secret["Password"] } } if($Secret.PSObject.Properties["UserName"] -and [string]::IsNullOrWhiteSpace($UserName)){ $UserName = [string]$Secret.UserName } if($Secret.PSObject.Properties["Password"]){ return ConvertTo-ConfigurationDataCredential -UserName $UserName -Password $Secret.Password } if([string]::IsNullOrWhiteSpace($UserName)){ throw "Secret [$Name] cannot be converted to [PSCredential] because no username was provided." } return ConvertTo-ConfigurationDataCredential -UserName $UserName -Password $Secret } if($ExpectedType -eq "securestring"){ if($Secret -is [System.Security.SecureString]){ return $Secret } if($Secret -is [System.Management.Automation.PSCredential]){ return $Secret.Password } if($Secret -is [System.Collections.IDictionary] -and $Secret.Contains("Password")){ $Secret = $Secret["Password"] }elseif($Secret.PSObject.Properties["Password"]){ $Secret = $Secret.Password } if($Secret -is [System.Security.SecureString]){ return $Secret } return ConvertTo-SecureString -String ([string]$Secret) -AsPlainText -Force } if($Secret -is [System.Management.Automation.PSCredential]){ return $Secret.GetNetworkCredential().Password } if($Secret -is [System.Security.SecureString]){ $Pointer = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($Secret) try { return [Runtime.InteropServices.Marshal]::PtrToStringBSTR($Pointer) } finally { [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($Pointer) } } if($Secret -is [System.Collections.IDictionary] -and $Secret.Contains("Password")){ return [string]$Secret["Password"] } if($Secret.PSObject.Properties["Password"]){ return [string]$Secret.Password } return [string]$Secret }