I am attempting to create a PowerShell Module that will dot-source any functions found with the subfolder "\Functions" using the following code:
# Get the path to the function files
$functionPath = $PSScriptRoot + "\Functions\"
# Get a list of all the function filenames
$functionList = Get-ChildItem -Path $functionPath -Include *.ps1 -Name
# Loop through all discovered files and dot-source them into memory
ForEach ( $function in $functionList ) {
. ( $functionPath + $function )
}
This is working fine if I drop all my functions directly inside the "\Functions" folder. However, this is not ideal as I don't think it allows for proper management of the function files at the later time (especially in a team environment where multiple SysAdmins could be modifying each function's script file at any given time). Additionally, some of the functions take input from CSV or Text files and it'll be much tidier to have those assets and the respective function contained within the same folder.
Hence my question: How do I accomplish what I'm trying to do above (i.e., dot-sourcing ALL functions that are found within the "\Functions" subfolder of $PSScriptRoot, even if they are located within subfolders?
PS. The end goal is to have a general purpose module that I distribute to all my admin workstations that will make available all the admin related scripts/functions we have created. Then as we add and remove scripts they are dynamically updated in the module each time PowerShell is launched.
Credit goes to Bryan Cafferky in this YouTube Video for the inspiration
You can simplify this a bit with a one-liner:
Get-ChildItem -Path "$PSScriptRoot\Functions\" -Filter *.ps1 -Recurse | %{. $_.FullName }
You were missing the -Recurse
parameter and could have used $function.FullName
rather than concatenating $functionPath
and $function