PS: Moving To Modules

1 minute read

Description:

So I have re-ordered most my scripts into Modules now and set them to follow this guide. I have also changed by scripts to be more portable with logging. I now have logs set to “$PSScriptRoot..\Logs\Scriptname.log” instead of forcing C:\scripts as I did before. This can be seen with my scripts here.

The next issue I have had is getting my helpers.ps1 to convert to a .psm1 and importing correctly. Essentially the issue is that I want script parameters to pass down to imported module parameters and I can’t get it to resolve correctly.

This is what works:

Begin
{
. "$PSScriptRoot\..\Private\helpers.ps1"
Set-Console
Start-Log
New-Alias -Name "Log" -Value Write-Log
}

But I would rather it be like:

Begin
{
Import-Module -Name "$PSScriptRoot\..\Private\helpers.psm1" -DisableNameChecking
Set-Console
Start-Log
}

… and in the helpers.psm1 I could have:

Function Write-Log
{
..
}
Set-Alias -Name Log -Value Write-Log
Function Test-IsAdmin
{}
Export-ModuleMember -Function * -Alias *

This would help so that I don’t have declare aliases in my begin blocks.

The ONLY thing that is stopping me is that I don’t want to have to put “-Logfile $Logfile” at the end of every “Start-Log”, “Write-Log”, or “Stop-Log” call in my script.

*If I dot source my helpers.ps1, the parameter from the script works with my functions and I don’t have to worry about it.

*If I try it with the import-module route, I get an error about Write-Log not having a -logfile parameter attached as it should.

It’s like the scripts “$Lofile” parameter doesn’t propagate down to the imported functions $Logfile variable when I import-module but it does when I dot source. I know it’s a scope issue, but I don’t know how to resolve it gracefully.

This isn’t that big of deal really, but I just thought I would post this to see if I can find a fix later on.

 


 

2018-01-02: Found the fix! Now in my begin block I use something like this:

Begin
{
Import-Module -Name "$Psscriptroot\..\Private\helpers.psm1"
New-Variable -Scope Global -Name Logfile -Value $Logfile
Set-Console
Start-Log
}

And since I get to move from .ps1 helper file to .psm1, I get to include the following as the last line: Export-ModuleMember -Function * -Alias *

See Part 2 to see my current setup.