1

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

phuclv
  • 37,963
  • 15
  • 156
  • 475
Kismet Agbasi
  • 557
  • 2
  • 8
  • 28
  • Why do you need the dot-sourcing? if you want all of these functions to be available anyway, why not either just add them to the top-level module or their own modules and (assuming they are 'installed' correclty) they will be automatically available to the users in powerShell? – boxdog Apr 04 '19 at 15:42
  • Because I don't want to manage multiple modules. Also, if I place all the functions inside a single module, I would increase my risk of possible file corruption or create problems down the road if someone checks out the file and makes a mistake - the whole module would break. This way, I isolate each function and the management thereof. – Kismet Agbasi Apr 04 '19 at 16:19

1 Answers1

3

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

Rich Moss
  • 2,195
  • 1
  • 13
  • 18