Computer Programming: PowerShell and Python Modules
What is a Module?
- We noted before that a function is a tool that does one task well
- We write the code once and re-use the tool wherever it is needed
- A module is just an extension of this concept
- Modules are collections of classes, functions, and other code
- These items are packaged up into a toolbox is outfitted for a particular task
- Take the Python
time
module for example, and you'll see that it is a module containing functions time-related tasks. That's its particular focus.
- Take the Python
Downloading and Importing Modules
- There are some modules that come packaged in default PowerShell and Python installations
- Others may be downloaded from an online repository
- Others may be developed locally
- Both PowerShell and Python will install modules to different directories depending on your privilege level
PowerShell
# Find a specific module
Find-Module -Name 'ModuleName'
# Search using wildcards
Find-Module -Name '*searchterm*'
# Install a module
# Install to the local user directory forcefully
Find-Module -Name 'ModuleName' | Install-Module -Scope CurrentUser -Force
# Import the module once downloaded
Import-Module 'ModuleName'
# List the commands provided by the module
Get-Command -Module 'ModuleName'
# Show the PowerShell module search path
# PowerShell will always prefer modules installed to directories at the top of the list
$env:PSModulePath
More info on creating your own PowerShell module: https://benheater.com/creating-a-powershell-module/
Python
- You can search for Python modules here: https://pypi.org/search
- Once you find a module you'd like to install you can use the
pip
module - The module will install to different locations depending on who you run the command as
# Bash shell
# Install a module using the PIP module
python -m pip install 'module_name'
# Print the Python module search path
# These are the locations Python will search for any modules
python -c 'import sys; print(sys.path)'
# Python Script
# Import your newly installed module
# Use within a script
# See module documentation for help on how to use functions within
import module_name