red888
red888

Reputation: 31652

powershell module startup commands

When writing powershell modules (in powershell) how do I have commands run when the module is imported?

When the user runs import-module mymodule I want the module to run some commands first to do some initial setup. how do I do this?

Upvotes: 4

Views: 1062

Answers (3)

briantist
briantist

Reputation: 47862

You can do the ScriptsToProcess thing as mentioned, but you can also just put the code directly into the .psm1 file (outside of a function definition). It all gets executed when the module is imported, so there's no need to use a separate file. (Anything written to standard output while the on-import code is executing is generally discarded.)

Upvotes: 5

Martin Lhotsky
Martin Lhotsky

Reputation: 456

One way to achieve that is to create module manifest when you have module ready. You can achieve that with following cmdlet

New-ModuleManifest

Check for more details:

Get-Help New-ModuleManifest

The option you're looking for is

-ScriptsToProcess <String[]>
    Specifies script (.ps1) files that run in the caller's session state when the module is imported. You can use these scripts to prepare an environment, just as you might use a login script.


    Required?                    false
    Position?                    named
    Default value                None
    Accept pipeline input?       false
    Accept wildcard characters?  false

Upvotes: 3

Martin Brandl
Martin Brandl

Reputation: 59001

If you have a PowerShell *.psm1module, you should also specify a module manifest (*.psd1). Within this manifest, you can spefiy an array of PowerShell scripts (*.ps1*) to invoke when the module gets loaded:

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

Upvotes: 2

Related Questions