Does Powershell have an equivalent to the bash subshell?

拈花ヽ惹草 提交于 2019-12-24 00:38:45

问题


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.


回答1:


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 ({...}).



来源:https://stackoverflow.com/questions/50246788/does-powershell-have-an-equivalent-to-the-bash-subshell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!