PowerShell: Setting an environment variable for a single command only PowerShell: Setting an environment variable for a single command only powershell powershell

PowerShell: Setting an environment variable for a single command only


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


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 wellwith-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 filesenv.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.