Pode.Web icon indicating copy to clipboard operation
Pode.Web copied to clipboard

Dot sourcing function not in scope

Open ili101 opened this issue 5 years ago • 2 comments

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'
}
  1. Dot sourcing/running Home.ps1 and Get-Noun is in Home.ps1 (uncomment it) it runs successfully.
  2. Dot sourcing/running Home.ps1 and dot sourcing Get-Noun from functions.ps1 like 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".
  3. & Home.ps1 and no matter where Get-Noun is loaded, when running the script I get "The term 'Get-Noun' is not recognized as a name of a cmdlet" on Public\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?)

ili101 avatar Dec 15 '20 00:12 ili101

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.

Badgerati avatar Dec 15 '20 11:12 Badgerati

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)?

IvanDrag0 avatar Sep 21 '21 18:09 IvanDrag0