Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Security.SecureString parameter does not accept strings

When passing a string as an argument to this parameter:

[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[Security.SecureString]$password=$(Throw "Password required.")

I get this error when using the -password parameter.

cannot convert type System.String to type System.Security.SecureString

If I don't pass the -password parameter, a prompt is shown and it accepts the input.

like image 227
Jelphy Avatar asked Mar 20 '17 11:03

Jelphy


2 Answers

You can't pass a string; you have to pass a secure string

function Get-PasswordThing {
    Param (
        [Parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [Security.SecureString]$password=$(Throw "Password required.")
    )

    Process {
        Write-Host "cool"
    }
}

[string]$password = "hello"
[Security.SecureString]$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
Get-PasswordThing -password $securePassword

# inline
Get-PasswordThing -password (ConvertTo-SecureString $password -AsPlainText -Force)
like image 193
gvee Avatar answered Oct 14 '22 18:10

gvee


Another option is to take the password as a String and then convert it to a SecureString within your function.

Function DoSomething {
Param (
    [Parameter(Mandatory=$true)]
    [ValidateNotNullOrEmpty()]
    [String]$password=$(Throw "Password required.")
)

$password = $password | ConvertTo-SecureString -AsPlainText -Force

#your script continues here
}
like image 23
henrycarteruk Avatar answered Oct 14 '22 18:10

henrycarteruk