简体   繁体   中英

Set Environment Variables From a .ps1 Script

I'm currently working on a Node.js project, and would like to automate the setting of environment variables. I've written a script ( set_env.ps1 ) that looks something like this:

Write-Host "Setting environment variables...";
$env:CLIENT_KEY="xxxxxxxxxxxxxxxx";
$env:CLIENT_SECRET="xxxxxxxxxxxxx";
[etc]

And I call this from some npm scripts:

"scripts": {
  "install:windows": "powershell ./set_env.ps1",
  "start": "npm run install:windows && node index",
  "monitor": "npm run install:windows && nodemon index"
},

It doesn't seem to work though. I can enter those same commands manually, one at a time, in the command line, and environment variables are set. Just by running the script, though, "Setting environment variables..." prints to the powershell prompt, but no variables get set.

Everything on the Internet seems to want to do this from the prompt, one env var at a time. This is extremely tedious with a long list of environment variables, and the embedded Powershell prompt in Webstorm has a habit of not accepting pasted strings.

Answering this question because it's likely somebody else will run into this issue.

As the two comments indicated, a Powershell script process's environment is lost on termination. Therefore, environment variables set inside the script won't get passed to the Powershell prompt.

Instead of chaining npm scripts to call everything we need, instead we can call npm run monitor or npm run start from the powershell script, like so:

Write-Host "Setting environment variables...";
$env:CLIENT_KEY="xxxxxxxxxxxxxxxxx";
$env:CLIENT_SECRET="xxxxxxxxxxxxxxxxxxxxxxx";
[etc]
[...]
Write-Host "Initializing process..."

npm run monitor

Then, we have our npm scripts like so:

"scripts": {
  "start:windows": "powershell ./start.ps1",
  "start": "node index",
  "monitor": "nodemon index"
}

To initiate, run npm run start:windows from the command prompt.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM