Search code examples
powershellpassword-encryptionpsexec

psexec in Powershell doesn't accept encrypted passwords


Powershell script executes script.ps1 on remote_machine

read-host -assecurestring | convertfrom-securestring | out-file D:\Script\cred.txt
$password = get-content D:\Script\cred.txt | convertto-securestring

$pwd = "plaintext_password"
$j = "remote_computer"
$comp = "\\"+$j

$command = "D:\PSTools\PsExec.exe $comp -u Administrator -p $pwd -accepteula powershell.exe c:\share\script.ps1"

Invoke-Expression $command

However, if I replace $pwd with $password, i.e.

$command = "D:\PSTools\PsExec.exe $comp -u Administrator -p $password -accepteula powershell.exe c:\share\script.ps1"

I get

The user name or password is incorrect.

I correctly entered in the password numerous times


Solution

  • This is returning a SecureString and not an unencrypted string:

    $password = get-content D:\Script\cred.txt | convertto-securestring
    

    When that variable gets used in a string, it expands to the type name System.Security.SecureString. You can use the script below to extract the encrypted password to plain text:

    $bstr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($password)
    $str =  [System.Runtime.InteropServices.Marshal]::PtrToStringBSTR($bstr)
    [System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr)
    $str