wontasia
wontasia

Reputation: 542

How to include functions in script files into PowerShell module

I'm using PowerShell 5.0 and trying to write a multi-files module.
The module's folder structure looks like this:

/FooModule
--- FooModule.psd1
--- FooModule.psm1
--- AnotherScriptFile.ps1

The manifest file FooModule.psd1 is customized like follows:

@{
    ModuleVersion = '0.0.1'
    GUID = ...
    Author = ...
    CompanyName = ..
    Copyright = ...
    Description = ...
    PowerShellVersion = '5.0'
    ClrVersion = '4.0'
    RootModule = "FooModule.psm1"
    FunctionsToExport = '*'
    CmdletsToExport = '*'
    VariablesToExport = '*'
    AliasesToExport = '*'
    # HelpInfoURI = ''
    # DefaultCommandPrefix = ''
}

I put these at the beginning of FooModule.psm1:

Push-Location $PSScriptRoot
.\AnotherScriptFile.ps1
Pop-Location

AnotherScriptFile.ps1 looks like this:

Write-Host "Imported!"
function Get-FooFunction($val)
{
    return "Foo Bar";
}

I think, when I import the module, it will read AnotherScriptFile.ps1's functions and variables into module's scope, and get exported. Sadly, after I imported the module with Import-Module .\FooModule.psm1 in the module's folder, calling Get-FooFunction gave me an error says Get-FooFunction does not exist, 'Write-Host "Imported!" was called though.

What's the correct way to make this work?

Upvotes: 2

Views: 2888

Answers (1)

Martin Brandl
Martin Brandl

Reputation: 58931

You can add the scripts in the ScriptsToProcess array within your module manifest:

# Script files (.ps1) that are run in the caller's environment prior to importing this module.
ScriptsToProcess = @('.\AnotherScriptFile.ps1')

Upvotes: 2

Related Questions