jackwmc4
jackwmc4

Reputation: 33

Processing a PowerShell SecureString as a parameter or console entry

I'm having a lot of difficulty with a PowerShell script that I'm trying to call a DirectoryServices query from. Currently, if I do a

$password = read-host "Password" -asSecureString

and subsequently

$credential = New-Object System.Management.Automation.PSCredential $username,$password

everything works fine. However if I try to pass the string parameter with a param($password) and then convert it to a secure string with this code:

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

After extensive debugging I can see this is working fine in terms of converting the string to a securestring, but I get a bad user/password from DirectoryServices when I use the parameter. Everything works fine when read from the console. Any ideas on what I can do to accept a parameter OR take console input in the absence of a parameter?

This is what I was hoping would work, but doesn't:

if($password -eq $null) {
    $password = read-host "Password" -asSecureString
} else {
    $password = ConvertTo-SecureString -AsPlainText -Force $password
}
$credential = New-Object System.Management.Automation.PSCredential $username,$password

Upvotes: 1

Views: 6236

Answers (1)

Wesley
Wesley

Reputation: 121

I recently created a script and was running into the same issue. The work around I found in my case was the following:

#Prompts for the username/password, enter the username in the form of DomainName\UserName
$Credential = get-credential

#Converts the password to clear text to pass it through correctly as passing through a secure string does not work.
$Password = $credential.GetNetworkCredential().password

#Converts the $Credential to just the DomainName/UsernName.
$Account = $credential.UserName

Hopefully this will work in your situation

Upvotes: 1

Related Questions