Quantcast
Channel: Windows PowerShell forum
Viewing all articles
Browse latest Browse all 21975

Functions from Module Scoping Question

$
0
0
Hello,

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.
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.

Some examples:

Module content:
————————————————————————————–
function Main
{

param
(
$sb2
)

$ses = New-PSSession -ComputerName sof-srv01

Execute -ses $ses -sb $sb2

}

function Execute
{

param (
$sb,
$ses
)

Invoke-Command -Session $ses -ScriptBlock $sb

}

Export-ModuleMember Execute,Main
————————————————————————————–

Script content:
————————————————————————————–
$var = ‘winrm’
$scr = {Get-Service $using:var}

Main -sb2 $scr
————————————————————————————–


Viewing all articles
Browse latest Browse all 21975

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>