Shaz Shaz - 3 months ago 7
PowerShell Question

How do I create an Environment variable in windows using Powershell that's accessible in a WebApi app?

How do I create an Environment variable in windows using Powershell that can then be accessed in an WebApi application using the

Environment.GetEnvironmentVariable()
method?

Here is what I've tried:

I created a powershell script called SetEnvironment.ps1. The contents of the file are:

[Environment]::SetEnvironmentVariable('TEST', 'testval')


then I ran the script using this command:

powershell -ExecutionPolicy ByPass -File .\SetEnvironment.ps1


Upon checking using
$Env:TEST
command, I found that environment path does not get saved.

If I add that command (
$Env:TEST
) within the script itself it works. But outside of that it doesn't work.

I've also tried killing explorer.exe and restarting it. Any ideas?

thanks

Answer

You are setting an environment variable only for the PowerShell process. You need to set one globally.

Use EnvironmentVariableTarget to specify the access you need

[Environment]::SetEnvironmentVariable('TEST', 'testval', [EnvironmentVariableTarget]::Machine)

Alternatively, if you create a process from PowerShell, that process will inherit any environment variables you might set. Do this if you can, as I generally discourage setting global environment variables.