Tuesday, January 4, 2011

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

I have some functions that contain functions. When I put the Functions in a .ps1 file and Dot Source directly the behave great but if those functions get imported in a module they fail to find the inner function with a CommandNotFound error. It does not matter if the functions are directly in a .psm1 file or if they are dot sourced by the .psm1 file they still fail to find the inner functions. Here are some code examples. Why is this? You can copy the below code into Powershell Console or ISE and run to see the errors.

function TestOuter{
param(
[
string]$Name,
[
scriptblock]$TestScript
)
function TestInner{
param(
[
int]$Count
)
Write-Host $Count
}
Write-Host $Name
& $TestScript
}
TestOuter -Name "Paul" -TestScript { TestInner -Count 10 }


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

No comments:

Post a Comment