leeand00
leeand00

Reputation: 26402

Does Powershell have an equivalent to the bash subshell?

One thing that's really great in linux bash shell is that you can define variables inside of a subshell and after that subshell completes the (environment?) variables defined within are just gone provided you define them without exporting them and within the subshell.

for example:

$ (set bob=4)
$ echo $bob
$

No variable exists so no output.

I was also recently writing some powershell scripts and noticed that I kept having to null out my variables / objects at the end of the script; using a subshell equivalent in powershell would clear this up.

Upvotes: 5

Views: 2524

Answers (1)

JohnLBevan
JohnLBevan

Reputation: 24470

I've not heard of such functionality before, but you can get the same effect by running something like the following:

Clear-Host
$x = 3
& {
    $a = 5
    "inner a = $a"
    "inner x = $x"
    $x++
    "inner x increment = $x"
}
"outer a = $a"
"outer x = $x"

Output:

inner a = 5
inner x = 3
inner x increment = 4
outer a = 
outer x = 3

i.e. this uses the call operator (&) to run a script block ({...}).

Upvotes: 5

Related Questions