views:

468

answers:

2

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.

A: 

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.

Andy Schneider
+2  A: 

Generally it would be better to pass info to the script via a parameter rather than a global variable. But if that is what you need to do and you want automatic cleanup of the variable then introduce a new scope like so:

& { $foo = 'bar'; $env:foo = 'bar'; ./myscript }

A couple of things to note about this. First, when the scope (scriptblock) is exited, $foo no longer exists. It existed only within the context of the scriptblock. However the environment variable $env:foo still exists because that truly is a global change. You can delete that variable like so:

Remove-Item Env:\foo
Keith Hill
Just a thought: Couldn't you just spawn a new PowerShell process, handing the scriptblock into it via the -Command parameter? That way you don't have to clean up the environment afterwards, since that will be contained in the child process. Although I am talking to a PowerShell MVP so this probably doesn't work :-)
Joey
Keith, we have a push-environmentblock and pop-environmentblock in Pscx for exactly this scenario ;-)
x0n
Johannes, that would work as well but somehow seems like cheating. :-) The PSCX Push/Pop-EnvironmentBlock (the one *I* changed to make work this way) would work but it doesn't have the automatic cleanup support that a scriptblock has.
Keith Hill