Search code examples
powershellvariablessecurestring

Saving secure string in persistent environment variable


So I'm wanting to save a secure string variable type for a local user. That way I can run a convertfrom-securestring to make rest api calls in a .ps1 file without the password being accessible. Is what I'm trying possible?

The code I'm using is below, but not yet working:

$PlainPassword = "atestpassword"
$SecurePassword = $PlainPassword | ConvertTo-SecureString -AsPlainText -Force
[Environment]::SetEnvironmentVariable('JiraCreds', $SecurePassword, "User")

Are environment variables only saved as strings without support for other data types?


Solution

  • Yes, environment variables are invariably strings, and a [securestring] instance cannot be used directly, because its string representation is simply its type name (System.Security.SecureString).

    However, you can pipe to ConvertFrom-SecureString to get a (still encrypted) string representation:

    $PlainPassword = "atestpassword" # Don't actually store this in your script.
    $SecurePassword = $PlainPassword | ConvertTo-SecureString -AsPlainText -Force | 
      ConvertFrom-SecureString
    [Environment]::SetEnvironmentVariable('JiraCreds', $SecurePassword, "User")
    

    To later use the environment variable to construct a [pscredential] instance (using the current user's username as an example):

    $cred = New-Object pscredential $env:USERNAME, (ConvertTo-SecureString $env:JiraCreds)