04 / RELIABLE NETWORK AUTOMATION · LESSON 13

Package reusable network helpers

Expose one stable subnet command from a local script module while keeping its converter private.

12 min · learn at your pace

Give callers a deliberate public command

The supplied SubnetTools.ps1 contains the converter and membership function you have already used. Package those helpers in NetworkTools.psm1, exporting only Test-IPv4Subnet. The numeric converter is an implementation detail and does not need to become part of the module's public interface.

Dot-source the helper from inside the module using $PSScriptRoot, which refers to the executing script's directory. This keeps the helper path independent of the caller's current working directory.

Import-Module '/home/user/Example.psm1' -Force
Get-NetworkLabLabel

Test the saved module, not only the editor session

A function defined in main.ps1 is not a saved reusable module. The checks import NetworkTools.psm1 and inspect its exported commands, then exercise boundary and invalid-input behaviour through that module.

Write module source from the editor with a single-quoted here-string so $PSScriptRoot is evaluated when the module runs, rather than while constructing the string. Use Export-ModuleMember -Function Test-IPv4Subnet to declare the public surface explicitly.

The helper must retain the previous contract: /0, /31, and /32 work; first and last addresses are members; malformed inputs throw. This local module needs no installation from the PowerShell Gallery and performs no network operations.

Go deeper

Read the official reference.

Try an example.ps1
Import-Module '/home/user/Example.psm1' -Force
Get-NetworkLabLabel
YOUR TURN

Put it into practice.

Create /home/user/NetworkTools.psm1. Load the supplied SubnetTools.ps1 from the module directory and export only Test-IPv4Subnet. Keep its existing membership and validation contract. The checker imports your saved module from a different working directory; defining commands only in main.ps1 is insufficient.

See an explained solution
One way to solve it.ps1
@'
. "$PSScriptRoot/SubnetTools.ps1"
Export-ModuleMember -Function Test-IPv4Subnet
'@ | Set-Content '/home/user/NetworkTools.psm1'
Import-Module '/home/user/NetworkTools.psm1' -Force

The module resolves its helper relative to its own file and exports one intentional public function. Callers can reuse the subnet contract without depending on the converter implementation.