2

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?

1 Answer 1

2

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')
Sign up to request clarification or add additional context in comments.

7 Comments

Thanks for you quick reply. I tried, but it didn't work :(
Another way would be to dot source the file (with another dot) in your FooModule.psm1. Try this: . .\AnotherScriptFile.ps1
I tried, but this time, an error occured, says ..\AnotherScriptFile.ps1 is not recognized as the name of a cmdlet, function,script file, or operable program.. Working directory was set to the root of the module though.
Sorry, due to the new line, I didn't see the space between the dot operator . and the file path .\AnotherScriptFile.ps1. I changed the 2nd line of FooModule.psm1 to -> .[space].\AnotherScriptFile.ps1, everything worked! Thank you very much!
Any idea why ScriptsToProcess doesn't work? Is it not able to load function definitions into the environment?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.