PowerShell: Setting an environment variable for a single command only

WindowsPowershellScriptingVariablesEnvironment

Windows Problem Overview


On Linux, I can do:

$ FOO=BAR ./myscript

to call "myscript" with the environment variable FOO being set.

Is something similar possible in PowerShell, i.e. without having to first set the variable, call the command, and then unset the variable again?

To be more clear about my use case - I don't want to use this as part of a script. Rather, I have a third-party script whose behavior I can control using environment variables, but, in this case, not command line arguments. So being able to alternate between typing

$ OPTION=1 ./myscript

and

$ ./myscript

would just be very handy.

Windows Solutions


Solution 1 - Windows

Generally, it would be better to pass info to the script via a parameter rather than a global (environment) variable. But if that is what you need to do you can do it this way:

$env:FOO = 'BAR'; ./myscript

The environment variable $env:FOO can be deleted later like so:

Remove-Item Env:\FOO

Solution 2 - Windows

I got motivated enough about this problem that I went ahead and wrote a script for it: with-env.ps1

Usage:

with-env.ps1 FOO=foo BAR=bar your command here

# Supports dot-env files as well
with-env.ps1 .\.env OTHER_ENV=env command here

On the other hand, if you install Gow you can use env.exe which might be a little more robust than the quick script I wrote above.

Usage:

env.exe FOO=foo BAR=bar your command here

# To use it with dot-env files
env.exe $(cat .env | grep.exe -v '^#') SOME_OTHER_ENV=val your command

Solution 3 - Windows

2 easy ways to do it in a single line:

$env:FOO='BAR'; .\myscript; $env:FOO=''
$env:FOO='BAR'; .\myscript; Remove-Item Env:\FOO

Just summarized information from other answers (thank you folks) which don't contain pure one-liners for some reason.

Solution 4 - Windows

To accomplish the equivalent of the Unix syntax, you not only have to set the environment variable, but you have to reset it to its former value after executing the command. I've accomplished this for common commands I use by adding functions similar to the following to my PowerShell profile.

function cmd_special()
{
  $orig_master = $env:app_master
  $env:app_master = 'http://host.example.com'
  mycmd $args
  $env:app_master = $orig_master
}

So mycmd is some executable that operates differently depending on the value of the environment variable app_master. By defining cmd_special, I can now execute cmd_special from the command line (including other parameters) with the app_master environment variable set... and it gets reset (or even unset) after execution of the command.

Presumably, you could also do this ad-hoc for a single invocation.

& { $orig_master = $env:appmaster; $env:app_master = 'http://host.example.com'; mycmd $args; $env:app_master = $orig_master }

It really should be easier than this, but apparently this isn't a use-case that's readily supported by PowerShell. Maybe a future version (or third-party function) will facilitate this use-case. It would be nice if PowerShell had a cmdlet that would do this, e.g.:

with-env app_master='http://host.example.com' mycmd

Perhaps a PowerShell guru can suggest how one might write such a cmdlet.

Solution 5 - Windows

You could do this by running the script as a Job:

Start-Job -InitializationScript { $env:FOO = 'BAR' } -FilePath .\myscript.ps1 |
    Receive-Job -Wait -AutoRemoveJob

You could also pass arguments to the script, using the ArgumentList parameter of Start-Job:

$jobArgs = @{
    InitializationScript = { $env:FOO = 'BAR' } 
    FilePath             = '.\myscript.ps1'
    ArgumentList         = 'arg1', 'arg2' 
}
Start-Job @jobArgs | Receive-Job -Wait -AutoRemoveJob

Advantages and disadvantages

  • You don't have to reset the environment variable after the script finishes (which would require try / finally to do it correctly even in the presence of exceptions).

  • The environment variable will be really local to the launched script. It won't affect other, possibly launched in parallel, jobs.

  • The script will run in its own, somewhat isolated environment. This means that the launched script can't set variables of the main script, it will have to use Write-Output to communicate back to the main script. This could be an advantage or a disadvantage, depending on the use case.

Solution 6 - Windows

Making a 'subshell' by invoking powershell with a script block allows you to scope the changes to the environment:

pwsh -Command { $env:MYVAR="myvalue"; .\path\to.exe }

Solution 7 - Windows

Considering that CMD is the native CLI on the Windows kernel (and is still the automation interface for lots of tools), you may be executing your PowerShell script with powershell.exe from the CMD prompt or an interface that accepts CMD console statements.

If you are using the -File parameter to pass your script to powershell.exe, no other PowerShell code can be used to set an environment variable for the script to access, so instead you can set your environment variables in the CMD environment before calling powershell.exe:

> set foo=bar && powershell.exe -File .\script.ps1

A single & will also work, but will allow the command to continue if the set failed for some reason. (Is this even possible? I have no idea.)

Also, it may be safer to wrap "foo=bar" in quotes so that nothing following gets passed to set as the variable contents.

Solution 8 - Windows

In my use case I needed to set an environment variable so I can use it within a Docker Compose script. within my Powershell Script I define the variable use a semicolon then call docker-compose on same line

$env:PLATFORM="linux/x86_64" ; docker-compose up -d --build

within docker compose I can now just use my ${PLATFORM} variable.

which looks like this

...
services:
  zookeeper:
    image: confluentinc/cp-zookeeper:latest
    platform: ${PLATFORM}
...

Solution 9 - Windows

You can scope variables to functions and scripts.

$script:foo = "foo"
$foo
$function:functionVariable = "v"
$functionVariable

New-Variable also has a -scope parameter if you want to be formal and declare your variable using new-variable.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionmiracle2kView Question on Stackoverflow
Solution 1 - WindowsKeith HillView Answer on Stackoverflow
Solution 2 - Windowskizzx2View Answer on Stackoverflow
Solution 3 - WindowsAlexander FadeevView Answer on Stackoverflow
Solution 4 - WindowsJason R. CoombsView Answer on Stackoverflow
Solution 5 - Windowszett42View Answer on Stackoverflow
Solution 6 - WindowsgolvokView Answer on Stackoverflow
Solution 7 - WindowsNReilinghView Answer on Stackoverflow
Solution 8 - WindowsRobert WaltersView Answer on Stackoverflow
Solution 9 - WindowsAndy SchneiderView Answer on Stackoverflow