Hello Power Users 🙂
I have the following case:
I`m using module that contains several functions, some of them are executing commends in remote sessions. These functions are used from Powershell Script.
This behavior is not reproduced when the functions are defined in the Script. I`m aware that Modules have their own "Scope"(or Context or whatever...), so I suppose the behavior is by design 🙂
I`m able to workaround it in two ways:
However it`s not so appropriate for my purpose.
My Question is:
$ses = New-PSSession -ComputerName sof-srv01
Execute -ses $ses -sb $sb2
Invoke-Command -Session $ses -ScriptBlock $sb
Main -sb2 $scr
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:
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.
Thank you Dave!
You must be logged in to reply to this topic.