.netwindowspowershellenvironment-variables

Creating Environment Variable Through Powershell


I am trying to create Environment variable for machine through powershell and passing the variables at run-time but It's not taking the variables. Powershell file: env_variable.ps1

Param (
  [Parameter(Mandatory=$True)]  [String] $VAULT_TEXT,
  [Parameter(Mandatory=$True)]  [String] $VAL
 )
[System.Environment]::SetEnvironmentVariable("$VAULT_TEXT","$VAL",[System.EnvironmentVariableTarget]::Machine)

Trying to trigger through Powershell:

$vault_text='IAndAAuth'
$val = get-content 'C:\vault\service_acct_pass'
C:\vault\env_variable.ps1 -VAULT_TEXT "$vault_text" -VAL "$val"

Result is coming like this: Key:VAULT_TEXT, Value:VAL in environments value.

Can you please help me in this.


Solution

  • Your method seems right and should be working. You can try doing it the old way by creating a registry key for your environment variable.

    User

    New-ItemProperty "HKCU:\Environment" -Name "your variable name" -Value "your value"
    

    Machine

    New-ItemProperty "HKLM:\System\CurrentControlSet\Control\Session Manager\Environment" -Name "your variable name" -Value "your value"