Quantcast
Channel: PowerShell.org » All Posts
Viewing all articles
Browse latest Browse all 13067

Reply To: Functions from Module Scoping Question

$
0
0

Ideally, you should pass in $var as a parameter to your module function. It’s cleanest if any input required by a function is defined as a parameter, and any output is returned via the output stream (or reference parameters.)

That said, there are some situations where you need to be able to read variables from the caller’s scope, and Script Modules do not automatically inherit those variables in the current versions of PowerShell. I’ve blogged about this a couple of times, and have a function to address it posted on the TechNet Gallery:

http://powershell.org/wp/2014/01/20/revisited-script-modules-and-variable-scopes/
http://powershell.org/wp/2014/01/13/getting-your-script-module-functions-to-inherit-preference-variables-from-the-caller/
http://gallery.technet.microsoft.com/Inherit-Preference-82343b9d

I’ve also submitted an article on this topic for the Hey, Scripting Guy blog, and in the course of reviewing it, I learned that the PowerShell team would consider this to be a design bug in Script Modules. At their suggestion, I submitted a bug report on the Connect site, but it will need to get quite a few “up” votes before it’s likely to be addressed. https://connect.microsoft.com/PowerShell/feedback/details/828782/functions-in-script-modules-do-not-inherit-variables-from-the-scope-of-their-caller

Anyhow, if you decide not to pass $var in to your function as a parameter, then you could use the Get-CallerPreference function (third link I posted in this thread) as follows, at the beginning of your module function:

Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState -Name var

At which point, you’d have a $var variable defined inside your module function’s scope, with the same value as the caller.


Viewing all articles
Browse latest Browse all 13067

Trending Articles