Reputation: 31652
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
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
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
Reputation: 59001
If you have a PowerShell *.psm1
module, 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