Skip to content

Instantly share code, notes, and snippets.

@steviecoaster
Last active November 22, 2024 15:00
Show Gist options
  • Save steviecoaster/158bfc86859d58d5263941e2b8fdab25 to your computer and use it in GitHub Desktop.
Save steviecoaster/158bfc86859d58d5263941e2b8fdab25 to your computer and use it in GitHub Desktop.
Write an encrypted Environment variable
function New-EncryptedEnvironmentVariable {
<#
.SYNOPSIS
Writes an Environment variable as a secure string using DPAPI
.DESCRIPTION
Writes an Environment variable as a secure string using DPAPI
.PARAMETER Scope
The scope of the variable. Can be machine, user, or process
.PARAMETER Name
The name of the environment variable
.PARAMETER Value
The value to encrypt
.EXAMPLE
New-EncryptedEnvironmentVariable -Scope Process -Name TestVar -Value SomeTestString
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory)]
[System.EnvironmentVariableTarget]
$Scope,
[Parameter(Mandatory)]
[ValidateScript( {
if ($_.Length -gt 32767) {
throw "Parameter value too long. Must be below 32767 characters"
}
else { $true }
})]
[String]
$Name,
[Parameter(Mandatory)]
[ValidateScript( {
if ($_.Length -gt 32767) {
throw "Parameter value too long. Must be below 32767 characters"
}
else { $true }
})]
[String]
$Value
)
end {
$string = $Value | ConvertTo-SecureString -AsPlainText -Force
$HumanReadableString = $string | ConvertFrom-SecureString
[System.Environment]::SetEnvironmentVariable($Name,$HumanReadableString,$Scope)
}
}
@markekraus
Copy link

you could replace

        [ValidateSet('Machine','User','Process')]
        [String]
        $Scope

with

        [System.EnvironmentVariableTarget]
        $Scope

That way it will work with the proper enum or string, do validation, and be a bit more future proof in case new Env scopes are added.

@steviecoaster
Copy link
Author

you could replace

        [ValidateSet('Machine','User','Process')]
        [String]
        $Scope

with

        [System.EnvironmentVariableTarget]
        $Scope

That way it will work with the proper enum or string, do validation, and be a bit more future proof in case new Env scopes are added.

Good shout. Thanks, Mark!

@jdhitsolutions
Copy link

jdhitsolutions commented Nov 22, 2024

I would recommend setting a default value for Scope or at least documenting what the different scopes mean.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment