I cannot pass the securestring to my cmdlet
I have a function that calls a cmdlet
Function connect-app([string]$host, [string]$user, [SecureString]$password, [switch]$passwordfile, [switch][alias("q")]$quiet)
Inside this function, I have a check for the presence $passwordfile
or$password
if ( -Not $passwordfile -and ($password -eq $null -or $password -eq ""))
{
# prompt for a password
[SecureString]$passwordenc = Read-Host -AsSecureString "Password";
}
else
{
$hash = Hash($host + "-" + $user);
[SecureString]$passwordenc = Get-Content "$env:USERPROFILE\$hash" | ConvertTo-SecureString;
}
Ultimately, if $quiet
provided, the variation on the cmdlet below is called
$expression = "Connect-Appliance -host " + $host + " -user " + $user + " -Password " + $passwordenc + " -Quiet";
Invoke-Express $expression
But for some reason I keep on facing this problem
Connect-Appliance: Unable to bind Password. Unable to convert value "System.Security.SecureString" of type "System.String" to type "System.Security.SecureString". On line: 1 char: 69 + Connect-Appliance -host 172.25.2.110 -user admin -Password System.Secur ... + ~~~~~~~~~~~~ + CategoryInfo: InvalidArgument: (:) [Connect -Appliance], ParameterBindingException + FullyQualifiedErrorId: CannotConvertArgumentNoMessage, CPowerCLI.ConnectAppliance
And I can't figure out why. At first I thought because I am providing a string, but the variable is declared as SecureString.
Can this be done?
What can I do is
$password = Read-Host -AsSecureString "Pass"
Connect-Appliance -host 172.25.2.110 -user admin -password $password -quiet
And it seems to be working fine. But when I call this from the psm1 file it fails with the error above.
thank
source to share
u should convert the protected string to Bstring
$Password = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($passwordenc))
Connect-Appliance -host 172.25.2.110 -user admin -password $password -quiet
Hope this helps.
source to share
anoopb, I ran into the same issue before. More FYI, but here's essentially the answer wrapped in a function:
function ConvertFrom-SecureToPlain {
param(
[Parameter(Mandatory=$true)][System.Security.SecureString] $SecurePassword
)
# Create a "password pointer"
$PasswordPointer = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecurePassword)
# Get the plain text version of the password
$PlainTextPassword = [Runtime.InteropServices.Marshal]::PtrToStringAuto($PasswordPointer)
# Free the pointer
[Runtime.InteropServices.Marshal]::ZeroFreeBSTR($PasswordPointer)
# Return the plain text password
return $PlainTextPassword
}
source to share