Dot sourcing function not in scope
Something strange I stumbled upon
Home.ps1
Import-Module Pode
Import-Module Pode.Web -Force
<#
function Get-Noun {
[CmdletBinding()]
param (
[String]$V1
)
'Ok'
}
#>
. .\functions.ps1
Start-PodeServer {
# add a simple endpoint
Add-PodeEndpoint -Address localhost -Port 8090 -Protocol Http
# set the use of templates
Use-PodeWebTemplates -Title 'Pester'
# convert module to pages
ConvertTo-PodeWebPage -Commands 'Get-Noun'
}
functions.ps1
function Get-Noun {
[CmdletBinding()]
param (
[String]$V1
)
'Ok'
}
- Dot sourcing/running
Home.ps1andGet-Nounis inHome.ps1(uncomment it) it runs successfully. - Dot sourcing/running
Home.ps1and dot sourcingGet-Nounfromfunctions.ps1like in the example the web page loads successfully but when submitting the form I get "The term 'Get-Noun' is not recognized as a name of a cmdlet". & Home.ps1and no matter whereGet-Nounis loaded, when running the script I get "The term 'Get-Noun' is not recognized as a name of a cmdlet" onPublic\Pages.ps1$cmdInfo = (Get-Command -Name $cmd).
Number 3 make some seance as it probably looks for the function in the global scope and it is not there, but number 2 is surprising as it suppose to behave identical. As the PowerShell documentation states "When you run a script that is dot sourced, the commands in the script run as though you had typed them at the command prompt." but somehow it behaves differently (PS bug?)
It appears to be intention; since Get-Command is running from the module's scope, it can't see any custom functions in the script's scope. I tried with Get-Item -Path Function:Get-Noun as well - same issue.
Changing the file to functions.psm1 and doing Import-Module on it did work though.
I might be able to add a -FilePath to ConvertTo-PodeWebPage so it can load them in-scope 🤔 I'll have a play with that later.
This is an issue I stumbled upon the other day. Does that mean that if I have a PS1 with custom functions, I'll need to change the name to .PSM1 and use Import-Module at the top of the script (the same way I'd import the Pode and Pode.Web modules)?