I have a collection of scripts / functions that I need often. So I want to store them in a separate module “Tools” and then store this psm1 file in a path from the PSMODULEPATH. For example in a file “C:\Users\myuser\Documents\WindowsPowerShell\Modules\Tools\Tools.psm1”.
Since I don’t want to copy all functions into one file, I want to load the actual scripts dynamically.
In the folder “C:\Users\myuser\Documents\WindowsPowerShell\Modules\Tools\Modules\MyFunc.ps1” I put a test function “MyFunc”.
# Test Function
function MyFunc {
[CmdletBinding()]
write-host "test"
}
I want to import / export this dynamically in Tools.psm1:
# dynamically import functions
# $moduleMember = @( Get-ChildItem -Path $PSScriptRoot\Modules\*.ps1 -ErrorAction SilentlyContinue )
# Test
$moduleMember = @( Get-ChildItem -Path C:\Users\myuser\Documents\WindowsPowerShell\Modules\Tools\Modules\MyFunc.ps1 )
# $moduleMember.member is now a system.string which contains
# "C:\Users\myuser\Documents\WindowsPowerShell\Modules\Tools\Modules\MyFunc.ps1"
# $moduleMember.basename ist now a system.string which contains "MyFunc"
# Dot source the files
Foreach($import in $moduleMember)
{
. $import.fullname -verbose
}
# This is not working
Export-ModuleMember $moduleMember.basename
# Even this is not working
$var = "MyFunc"
Export-ModuleMember $var
# This is working
Export-ModuleMember "MyFunc"
If i start powershell and type
get-module Tools -ListAvailable
i see the exported command “MyFunc” only if i exported it with a literal string
and then you put each individual function in its own *.ps1 file in the same folder. Especially when your module has a lot of functions that’s a lot easier to maintain.
(notice the dot in front of $_.FullName separated by a space. That’s called dot sourcing and is used to import external scripts into the same scope of the current executed script.