views:

32

answers:

2

I need to run scriptblocks/scripts from the current top-level shell and I want them to leave the global scope unmodified.

So far, I've only been able to think of the following possibilities:

 powershell -file <script>
 powershell -noprofile -command <scriptblock>

The problem is, that they are very slow.

For instance, I would like to be able to do:

mkdir newdir
cd newdir
$env:NEW_VAR = 100
ni -item f 'newfile.txt'

...so that my shell's working dir wouldn't change and $env:NEW_VAR wouldn't be set in the global scope.

Are there any more alternatives to accomplish this?

A: 

There is no such thing as a global environment. When spawning a new process, the OS creates a copy of the environment for the new process.

if you run the scripts in a separate process, when it leaves everything will be intact.

Peter Tillemans
I think I meant "scope", not "environment".
guillermooo
A: 

I don't know about any other alternative. Environment variables are kept per process as @Peter answered.

Futhermore if you create new dir and a file in there, then you alter the global environment. So the script is not completely innocent.

In your case I would run new proccess as you suggested.
If it is too lazy, place it into a script and wrap it into try/finally:

--- script.ps1
push-location
try {
  mkdir newdir
  cd newdir
  $env:NEW_VAR = 100
  ni -item f 'newfile.txt'
} finally {
  pop-location
  # delete dir/file?
  remove-item env:NEW_VAR
}
stej