0

I am creating a file that has password with secureString as below

[string][ValidateNotNullOrEmpty()]$secureStringPwd = "password123"
$secpasswd = ConvertTo-SecureString $secureStringPwd -AsPlainText -Force
$secureStringText = $secpasswd | ConvertFrom-SecureString 
Set-Content "C:\folder\user.txt" $secureStringText

Now I am trying to retrieve the password the following way

$Password = Get-Content "C:\folder\user.txt" | ConvertFrom-SecureString 

$creds = New-Object System.Management.Automation.PSCredential ("user", $Password)
$creds.Password
$creds.UserName

But I am getting an error as below:

New-Object : Cannot find an overload for "PSCredential" and the argument count: "2".
At line:1 char:10
+ $creds = New-Object System.Management.Automation.PSCredential ("user ...
+          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [New-Object], MethodException
    + FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand
meallhour
  • 13,921
  • 21
  • 60
  • 117
  • If you want to securely store credentials without doing the dirty work yourself, check out my recent answer to a related question: [What is the best way to store account credentials (especially password) for an automated email script?](https://stackoverflow.com/questions/50917375/what-is-the-best-way-to-store-account-credentials-especially-password-for-an-a/50918111#50918111) – boxdog Jun 22 '18 at 17:41
  • See this MS GitHub doc: https://github.com/dotnet/platform-compat/blob/master/docs/DE0001.md – jhyry-gcpud Sep 30 '21 at 03:33

1 Answers1

2

You need to Convert the password from the text file back into a Secure String

$Password = Get-Content "C:\folder\user.txt" | ConvertTo-SecureString

Also you need to get the password into plain text by using the Network Credentials

$creds.GetNetworkCredential().Password

Here is a working example

[string][ValidateNotNullOrEmpty()]$secureStringPwd = "password123"
$secpasswd = ConvertTo-SecureString $secureStringPwd -AsPlainText -Force
$secureStringText = $secpasswd | ConvertFrom-SecureString 
Set-Content "C:\folder\user.txt" $secureStringText

$Password = Get-Content "C:\folder\user.txt" | ConvertTo-SecureString 

$creds = New-Object System.Management.Automation.PSCredential ("user", $Password)
$creds.GetNetworkCredential().Password
$creds.UserName
ArcSet
  • 6,518
  • 1
  • 20
  • 34