简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM