Set Environment Variables From a .ps1 Script Set Environment Variables From a .ps1 Script powershell powershell

Set Environment Variables From a .ps1 Script


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.