Last active
          November 22, 2024 15:00 
        
      - 
      
 - 
        
Save steviecoaster/158bfc86859d58d5263941e2b8fdab25 to your computer and use it in GitHub Desktop.  
    Write an encrypted Environment variable
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | 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) | |
| } | |
| } | 
you could replace
[ValidateSet('Machine','User','Process')] [String] $Scopewith
[System.EnvironmentVariableTarget] $ScopeThat 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!
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
  
            
you could replace
with
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.