Search code examples
powershell-3.0securestring

I can't seem to pass a securestring to my cmdlet


I've got a function which calls a cmdlet

Function connect-app([string]$host, [string]$user, [SecureString]$password, [switch]$passwordfile, [switch][alias("q")]$quiet)

Inside of this function, I've got a check for if $passwordfile or $password is provided

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 is supplied, then a variation of the cmdlet below is called

$expression = "Connect-Appliance -host " + $host + " -user " + $user + " -Password " + $passwordenc  + " -Quiet";
Invoke-Express $expression

But for some reason, I keep running into this issue

Connect-Appliance : Cannot bind parameter 'Password'. Cannot convert the "System.Security.SecureString" value of type "System.String" to type "System.Security.SecureString". At 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. I thought at first, it's because I'm providing a string but the variable is declared as a SecureString.

Is it possible to do this?

What I can do is

$password = Read-Host -AsSecureString "Pass"
Connect-Appliance -host 172.25.2.110 -user admin -password $password -quiet

And that seems to work just fine. But when I call that from the psm1 file, it doesn't work with the error above.

thanks


Solution

  • u should convert back the secure 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
    

    i hope this helps.