Saving credentials and secrets inside your code is a very bad idea and should be avoided. PowerShell has built-in commands to export and import encrypted data in your code.

There might be a lot of ways to achieve this, but this is how I like to do it. This is very elegant and easy to implement.

Let’s say we have a secret password that we want to secure and avoid saving in the source code.

$secretPW = “SecretPassword” | ConvertTo-SecureString -AsPlainText -Force

We can export this variable to an encrypted XML file with

$secretPW | Export-Clixml -Path .\secret.xml

The password is not human readable:

To import this file use

$secretPW = Import-Clixml -Path .\secret.xml

The plain-text password can be obtained through (I had to split the command into two lines)

[System.Runtime.InteropServices.Marshal]::
PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secretPW))

Just outputting the variable won’t show the password, because the variable is a System.Security.SecureString object.

Credentials can also be saved this way:

$credentials = Get-Credential

You can show the plain-text password with

$credentials.GetNetworkCredential().password

$credentials | Export-Clixml -Path .\credentials.xml

Only the username is shown in clear text.

Same thing again with the import

$credentials = Import-Clixml -Path .\credentials.xml

$credentials.GetNetworkCredential().password

The password can be decrypted by the same user that created the XML file on that specific computer.

References:

https://devblogs.microsoft.com/scripting/decrypt-powershell-secure-string-password/

https://pscustomobject.github.io/powershell/functions/PowerShell-SecureString-To-String/