CTS – Your Technology Partner

PowerShell Modules

Written by Cody Luu on March 28, 2016

PowerShell is a scripting language used for task automation and administration on Windows machines. Scripting simple, repetitive tasks such as report parsing and deployment can save time and eliminate manual errors.

It can be difficult to manage your scripts as you accumulate more over time. When I want to run a script, I follow these steps:

  1. Click on PowerShell ISE
  2. Locate and open the particular script(s) and dependencies
  3. Run the script so that it’s available in session

This process does not scale well when the scripts and their dependencies span multiple files and locations.

We need a solution that allows PowerShell objects like variables and functions to be loaded into session with a simple shell command. This solution should include script management and simplify the process above.

PowerShell Modules is a feature that allows developers to package, reuse, and deploy scripts. Modules are simple to implement. To begin, open up Notepad. Save the file with a PSM1 extension, and drop it in its own directory in any of the following locations that PowerShell searches when you load a module.

  • %UserProfile%\Documents\WindowsPowerShell\Modules
  • %Windir%\System32\WindowsPowerShell\v1.0\Modules
  • %ProgramFiles%\WindowsPowerShell\Modules

The following helper function simply parses a report definition file for report names, stored procedures, and other metadata, but depends on another configuration file for variable management.

powershell pic 1

Here we use ‘dot’ notation (line 3) to import configuration variables from another file. This approach adds an extra step to execution because we need to run the configuration script before using the function in session. A better approach would be to convert the script and configuration variables into two separate modules and change the dot notation to an Import-Module command.

powershell pic 3

Here is the modified Get-RDLDataSetInfo function that removes the call to Get-ScriptDirectory (line 4) and adds an Import-Module command (line 1) to import our Variables module:

4powershell pic 4

Now that we have converted the scripts to modules and modified the import method, we simply pull up the PowerShell terminal and run the following:

powershell pic 5

The command ‘Import-Module SSRSHelpers’ will search through the default directories listed above and load the named module. This allows us to import modules and execute them from any directory.

When we call Get-RDLDataSetInfo, the internal ‘Import-Module’ cmdlet executes which brings the variables into session for us. If you run into restriction issues, follow this tutorial.

By using Import-Module, we no longer have to run individual scripts in ISE, which simplifies our scripting workflow.

 

Comments

comments