bharath kumar
bharath kumar

Reputation: 69

How to pass the password as argument in Powershell script and convert to secure string

I am using below powershell script to execute

param([string]$Server,[string]$locusername,[string]$locpassword)

$password = '$locpassword' | ConvertTo-SecureString -asPlainText -Force
$username = $locusername 
$cred = New-Object System.Management.Automation.PSCredential($username,$password)

and i am getting error

Cannot bind argument to parameter 'String' because it is null. + CategoryInfo : InvalidData: (:) [ConvertTo-SecureString], ParameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ConvertToSecureStringCommand

Upvotes: 6

Views: 32195

Answers (6)

SPGrinch
SPGrinch

Reputation: 31

(
    [Parameter(Position=1,Mandatory=$True,HelpMessage="Source UserName")]
    [string]$srcUsername,
    [Parameter(Position=2,Mandatory=$True,HelpMessage="Source Password")]
    [SecureString]$strsrcPassword,
    [Parameter(Position=3,Mandatory=$True,HelpMessage="Destination UserName")]
    [string]$dstUsername,
    [Parameter(Position=4,Mandatory=$True,HelpMessage="Destination Password")]
    [SecureString]$dstPassword
)

Upvotes: 1

Balamurugan
Balamurugan

Reputation: 1

it will be work

$password = ConvertTo-SecureString -String "******" -AsPlainText

Upvotes: 0

Musa Ugurlu
Musa Ugurlu

Reputation: 11

change this line

$password = '$locpassword' | ConvertTo-SecureString -asPlainText -Force

with this:

$password = ($locpassword | ConvertTo-SecureString -asPlainText -Force)

Upvotes: 1

Nkosi
Nkosi

Reputation: 247088

As already mentioned by @Swonkie in the comments

There is no need to quote the parameter. Just use the parameter as provided.

param([String]$Server, [String]$locusername, [String]$locpassword)
process {
    #NOTE: no quotes on parameter $locpassword
    $secure_password = ConvertTo-SecureString -String $locpassword -AsPlainText -Force
    $credential = New-Object System.Management.Automation.PSCredential($locusername, $secure_password)
    #...other code
}

If you are still getting that error then review the value stored in $locpassword as it may have been assigned a $null value.

Upvotes: 4

Esperento57
Esperento57

Reputation: 17472

use $locpassword or "$locpassword" , not '$locpassword' ;)

example here

Upvotes: -1

ClumsyPuffin
ClumsyPuffin

Reputation: 4059

instead of using single quotes use double quotes , for string expansion

$password = "$locpassword" | ConvertTo-SecureString -asPlainText -Force 

full code:

param([string]$Server,[string]$locusername,[string]$locpassword)

$password = "$locpassword" | ConvertTo-SecureString -asPlainText -Force 
$username = $locusername 
$cred = New-Object System.Management.Automation.PSCredential($username,$password)

Upvotes: -2

Related Questions