4

I need to set the environment variable from a batch file. In Linux, I could use this:

source key.sh

How do I do this in PowerShell? When I ran key.bat, it gave an error. I ran .\key.bat and it set the variable, but it doesn't show when I run $env:KEY.

5
  • 1
  • 1
    @Seth I found that page on my searches, but it doesn't say anything about batch files and keeping the environment variables the batch file sets.
    – Chloe
    May 2, 2017 at 6:28
  • You can't do it simply as a .bat script runs in a child process (which does not transfer environment variables change to the parent one). Related: How can I source variables from a .bat file into a PowerShell script?.
    – JosefZ
    May 2, 2017 at 6:46
  • In all honesty, if you need to run PowerShell code use the PowerShell and not a batch file. Even within the batch you could run the PowerShell and let it directly execute commands (assuming your execution policy permits it). The page further details that you need to use the .Net methods to make it "more permanent". You might want to clarify a bit what exactly you want to run and what your expected result would be.
    – Seth
    May 2, 2017 at 6:53
  • You can also pass a variable set in batch to a PowerShell script or vice versa depending on what exactly you are trying to do. I think clarification is needed so it's clear how you have your process setup. May 5, 2017 at 12:31

1 Answer 1

1

If you have powershell availible just invoke .net inside powershell to set the Environment it according to your needs.

[System.Environment]::SetEnvironmentVariable($Name, $Value, [System.EnvironmentVariableTarget]::Machine)
//[System.EnvironmentVariableTarget]::Machine
//[System.EnvironmentVariableTarget]::User
//[System.EnvironmentVariableTarget]::Process

See SetEnvironmentVariable documenation:
https://docs.microsoft.com/en-us/dotnet/api/system.environment.setenvironmentvariable?view=net-6.0

If you need to modify the a user environment under batch, I would change the registry.

See reg add documentaion:
https://docs.microsoft.com/de-de/windows-server/administration/windows-commands/reg-add

reg add HKEY_CURRENT_USER\Environment /v "TestTemp" /t REG_EXPAND_SZ /d "C:\temp"

Take care that the called process is a sub process of the parent and not a separate one, cause if the process call chain breaks all process environment variables are lost.

By the way the replacement of source command in powershell is different question.

See Microsoft documentation:
https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_scripts?view=powershell-7.2

source key.sh

would be

. "key.ps1"

in PowerShell.

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .