liveBook · Manning

Module-level variable

As explained in Learn PowerShell Scripting in a Month of Lunches, Second Edition: Write and organize scripts and tools

A module-level variable is a variable declared in a PowerShell module outside functions and shared by code in that module.

A module-level variable is declared outside functions and shared by code inside a PowerShell module. It is useful for reusable configuration, such as a database connection string, across several functions. section 26.3

Use module scope deliberately:

  • Export the variable when callers need it; loading the module adds it to the global scope, and unloading removes it. section 26.3
  • Leave helper functions unexported when they support the module internally rather than providing a public command. section 26.3

Connection-string configuration

A disk-information module stores its SQL Server connection string in $DiskInfoSqlConnection. New-DiskInfoSQLTable reuses that value to open the connection and create the diskinfo table when it does not already exist.

How Learn PowerShell Scripting in a Month of Lunches, Second Edition: Write and organize scripts and tools covers it

How deep it goes
Defines scope, export behavior, and module lifecycle, but does not develop broader variable-scope internals.
Examples
Uses a SQL Server connection string shared by disk-information and table-creation commands.
What it assumes
Assumes familiarity with PowerShell functions and modules while demonstrating export behavior through a database example.
What you can do after
Apply it via a PowerShell module to share configuration while controlling which variables and functions become public.
How it connects
Connects module scope with PowerShell modules, functions, global scope, and module exports.

This explainer was generated by Manning's knowledge graph from the text of Learn PowerShell Scripting in a Month of Lunches, Second Edition: Write and organize scripts and tools. The section links point to the parts of the book it draws on.