Every once in awhile I forget something I know, I know. Not sure why, but for a quick moment, I suddenly couldn’t remember which can access what. Can a nested, or child, function, access the variable in the containing, or parent, function, or is it the other way around? That is, can a containing, or parent, function access the variable in the nested, or child, function? Even as I write this, I still can’t believe that for a moment I forgot what I’ve known for so long.
Duh. A nested or child function can access a variable assigned in the containing or parent function. If the child function cannot find a declared variable inside itself, it’ll go upward in scope to its mom or dad, and ask if they have the variable assigned, and if so, they can borrow it. Being good parents, they offer it if they have it.
It’s so obnoxious that in a quick moment, I wasn’t sure, even though I’ve pictured it in my own head multiple times, as well as relied on it. Anyway, here’s an example that does prove that a nested function will go upward to find a variable, if it’s not been assigned inside itself.
Function AAA { 'In function AAA.' Function BBB { 'In function BBB.' $x = 5 } $x BBB } AAA Function CCC { 'In function CCC.' $x = 5 Function DDD { 'In function DDD.' $x } DDD } CCC
In function AAA. In function BBB. In function CCC. In function DDD. 5
This got me wondering, how far up will it go!? I assume it’ll go up and up and up, and well I was right. Take a look at this example. I guess if I had to forget something so simple that at least I got an opportunity to build this example. Enjoy the weekend!
Function Top { $x = 10 "0. Assigned `$x with $x." "1. Inside the $($MyInvocation.MyCommand.Name) function." Function MidTop { "2. Inside the $($MyInvocation.MyCommand.Name) function." Function MidBottom { "3. Inside the $($MyInvocation.MyCommand.Name) function." Function Bottom { "4. Inside the $($MyInvocation.MyCommand.Name) function." If (Get-Variable -Name x -Scope Local -ErrorAction SilentlyContinue) { '5. Can find the variable in the local scope.' } Else { '5. Cannot find the variable in the local scope.' } "6. The value of `$x is $x." } # End Function: Bottom. Bottom } # End Function: MidBottom. MidBottom } # End Function: MidTop. MidTop } # End Function: Top. Top
0. Assigned $x with 10. 1. Inside the Top function. 2. Inside the MidTop function. 3. Inside the MidBottom function. 4. Inside the Bottom function. 5. Cannot find the variable in the local scope. 6. The value of $x is 10.
Update: I made a few modifications to the above function. Now, it indicates that it cannot find the $x variable in the local scope of the Bottom function. That’s one way to help prove it goes upward through the parent functions looking for a value for $x.