Tuesday, January 4, 2011

Solved: Powershell fails as a functional language if commands are in modules.

 

the issue comes down to the scope that the scriptblock being passed into the function gets bound. In the original example the scriptblock was being bound to the callers scope which can not access anything in the module except what was imported into the scope. The fix turns out to be explicitly binding the scriptblock to the modules scope. See the fixed example below. Thanks go out to @Oisin for the fix.

New-Module -Name 'Testing' -ScriptBlock {
function TestOuter{
param(
[
string]$Name,
[
scriptblock]$TestScript
)
function TestInner{
param(
[
int]$Count
)
Write-Host $Count
}
Write-Host $Name
$Mod = Get-Module Testing
& ( $Mod.NewBoundScriptBlock($TestScript) )
}
}
| Import-Module -Force -Global
TestOuter -Name "Paul" -TestScript { TestInner -Count 10 }
Remove-Module Testing -Force