PowerShell provides a simple technique to view the contents of a function, e.g.
Get-Content function:MyFuncName # (A)
or equivalently
(Get-ChildItem function:MyFuncName).definition # (B)
where MyFuncName is the name of my function. That is great for simple functions (i.e. functions that use only base language constructs and do not call other functions). But consider the function foo shown below that contains a call to the function bar. In a typical scenario these would both be contained in the same module whose public API consists solely of the function foo and thus it is the only function exported.
function foo ()
{
$p = bar "here"
"result is '$p'"
}
function bar ([string] $s)
{
$s + $s
}
Export-ModuleMember foo
Is there any way to view the nested, non-exported functions (like function bar) within another function in a fashion comparable to (A) or (B) above? (That is, without opening the .psm1 file in an editor 🙂
I’m not sure if you can do it for a particular function in a module but you can do it for the whole module:
I think the fact that function foo calls function bar is not known until runtime.
Update
Where there’s a will, there’s a way 🙂 Here’s how you can access private module members. Invoke the module with a scriptblock. Inside the scriptblock the private members are visible.
Thanks to PowerTips 🙂 http://powershell.com/cs/blogs/tips/archive/2009/09/18/accessing-hidden-module-members.aspx
Update 2
After finding the little PowerTip snippet I was kinda curious what was really going on… The snippet uses the call operator
&with two arguments.System.Management.Automation.PSModuleInfo)So what’s really going on is the
Invokemethod of thePSModuleInfotype is being called. The code in the script block runs within the same session state as the rest of the module code so it has access to the private members. This code does the exact same thing as the PowerTip snippet:Check out the invoke method here: http://msdn.microsoft.com/en-us/library/system.management.automation.psmoduleinfo.invoke(v=vs.85).aspx