> For the complete documentation index, see [llms.txt](https://x7331.gitbook.io/notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://x7331.gitbook.io/notes/windows-shells/powershell/cmdlets-and-modules.md).

# CmdLets & Modules

A [cmdlet](https://learn.microsoft.com/en-us/powershell/scripting/lang-spec/chapter-13?view=powershell-7.2) is a single-feature command that manipulates objects in PowerShell. Cmdlets are written in C# or other languages and then complise for PowerShell usage. PowerShell [modules](https://learn.microsoft.com/en-us/powershell/scripting/developer/module/understanding-a-windows-powershell-module?view=powershell-7.2) is similar to a script; it can contain cmdlets, functions, other scripts, etc.

1. The most basic way to create a module is to save a Windows PowerShell script as `.psm1`. This is the "meat" of the module.
2. A Powershell data file (`.psd1`) is called a **module manifest file** and contains information such as version numbers, authors, cmdlets used, etc.

[PowerShell Gallery](https://www.powershellgallery.com/) is the best place to search for modules, scripts, etc. We can interact with it directly through PowerShell with the `PowerShellGet` cmdlet.

```powershell
# list modules parameters
Get-Command -Module PowerShellGet
# find a specific module
Find-Module -Name <module>
# install module
Install-Module -Name <module>
```

PowerShell will auto-import a module installed the first time we run a cmdlet or function from it. This is not true for modules that we bring onto the host from elsewhere, e.g. GitHub.

## Using Modules

```powershell
# list loaded modules
Get-Module
# list available modules (installed but not loaded into the session)
Get-Module -ListAvailable
# load a module in the current session
Import-Module <my_module.ps1>
```

It is possible to permanently add a module by adding the files to the referenced directories in the `PSModulePath`.&#x20;

```powershell
$env:PSModulePath
```

After loading the module, we can list its parameters.

```powershell
Get-Command -Module <module>
```

## Execution Policy

A host's execution policy might prevent us from running scripts.

```powershell
# check execution policy state
Get-ExecutionPolicy
Restricted
# changing execution policy (undefined -> no interecation limits)
Set-ExecutionPolicy undefined
```

Another way to bypass the execution policy and not leave a persistent change (as above) is to change it at the process level using `-scope`. This way the change will be reverted once we close the session.

```powershell
Set-ExecutionPolicy -scope Process
Get-ExecutionPolicy -List
```

> [Execution Policy bypasses](https://www.netspi.com/blog/technical/network-penetration-testing/15-ways-to-bypass-the-powershell-execution-policy/).
