Click here to Skip to main content
15,881,172 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I want to set an environment variable automatically, without executing the cmd first, then echo the environment to show the value of the environment variable.

I tried this code, I store the value as cmd file that I want to set as an environment variable. If I want to show the environment value, I have to execute the cmd file first.

What I have tried:

Param(
    [Parameter(Mandatory)] [string] $FilePath,
    [Parameter(Mandatory)] [string] $Key,
    [Parameter(Mandatory)] [string] $Variable_Name,
    [Parameter(Mandatory)] [string] $Store
)

$Found = $False
$FileContents = switch -File $FilePath {
    $Key    { $Found = $True }
    default {
        if ($Found) {
            $_.Substring(1);
            break
        }
    }
}
$FileContents

$Path_Store = $Store
$Output = "set" + " " + $Variable_Name + "=" + $FileContents |
          Out-File $Path_Store\$Variable_Name.cmd -Encoding Ascii




My expectation, once I execute the PowerShell script, I can directly show the environment variable
Posted
Updated 19-Feb-20 10:43am

1 solution

What's wrong on changing environment variables using Environment provider like
$env:variableName = <variableValue> ?
(see about_Environment_Variables - PowerShell | Microsoft Docs[^]: When you change environment variables in PowerShell, the change affects only the current session. This behavior resembles the behavior of the Set command in Windows-based environments and the Setenv command in UNIX-based environments.)

If a variable name is stored in a Powershell variable, you can utilize methods of the System.Environment class (see Environment Class (System) | Microsoft Docs[^]) to do something like
$Variable_Name = variableName;
[System.Environment]::SetEnvironmentVariable( $Variable_Name, <variableValue>);

In both occurrences, the <variablevalue> could be a Powershell literal string e.g. "some_path", or a string variable, e.g. $FileContents.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900