Sunday, 1 April 2018

PowerShell modules

Overview of PowerShell Modules

A module in PowerShell is basically a script with exposed members, such as Functions and Variables. It's best for a specific module to serve a singular purpose. There are four kinds of PowerShell module. (As documented in this Microsoft link: click here.)
  • Script Modules -- PSM1 files that usually contain functions, but can contain any valid PowerShell code.
  • Binary Modules -- Compiled DLL files, which can be created in .NET languages like C#, F# or VB.
  • Manifest Modules -- These are Script Modules which contain a manifest.
  • Dynamic Modules -- In memory modules which haven't been persisted to permanent storage.

How To Create A PowerShell Module

At the basic level, a PowerShell module is a text file with a ".psm1" extension. Here's an example:
  • # A private variable.
  • $prefix = 'Some text'

  • Function Get-Prefix
  • {
  •     $prefix
  • }

  • Function Append-Prefix ($suffix)
  • {
  •     $prefix + $suffix
  • }

  • Function HiddenFunc
  • {
  •     # do something...
  • }

  • Export-ModuleMember -Function '*-*'

Here the functions "Get-Prefix" and "Append-Prefix" are exposed, but the variable "$prefix" and function "HiddenFunc" are not exposed.

How To Use A PowerShell Module

A module can be imported into the PowerShell console directly, and also into script files. Importing the module brings all of the functions and variables into that PowerShell session. To do this you can import a module called "C:\foobar.psm1" in the following way:
Import-Module C:\foobar.psm1