I`m using module that contains several functions, some of them are executing commends in remote sessions. These functions are used from Powershell Script.
The issue is that when function refers to variable from the local computer using the ā$Using:varā syntax, it does not tries to access the variables that is defined in Script scope.
The exception is:
āInvoke-Command : The value of the using variable ā$using:varā cannot be retrieved because it has not been set in the local session.ā
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:
Using the ā$Using:global:varā syntax in the script block or dot source the script.
However it`s not so appropriate for my purpose.
My Question is:
Can I force the Functions that comes from Module to behave the same way as if they are defined in the Script.
Any other suggestions are welcome.
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:
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.