On Linux, I can do:
$ FOO=BAR ./myscript
to call \"myscript\" with the environment variable FOO being set.
Is something similar pos
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.
https://gist.github.com/bobalob/6632690e33747c13a8c00875ee686be2
$ENV:ARM_SUBSCRIPTION_ID = ""
$ENV:ARM_CLIENT_ID = ""
$ENV:ARM_CLIENT_SECRET = "" # This should end with an '=' symbol
$ENV:ARM_TENANT_ID = ""
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
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.
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.
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