Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between using module, Import-Module, and #requires -Modules

Tags:

powershell

Is there any detailed reference for how these 3 different methods for importing PowerShell modules work? I'm currently seeing different behavior with using module vs Import-Module in a script.

It seems importing dependencies works differently. Using Import-Module in order of dependencies can resolve the issue, but with using module it doesn't appear to be able to resolve dependencies.

Is this script dependent on how the import statements are created or is there a documented difference in how these different commands work?

like image 700
Steve Avatar asked Feb 26 '26 14:02

Steve


1 Answers

I didn't find any guidelines either, but I made the following comparison to make some sense of what is what.

Import-Module

Well, it's a cmdlet. That means it

  • Accepts pipelines: 'PSReadLine','PSColor' | Import-Module
  • Accepts splatting: $params = @{Name = 'PSReadLine'; OutBuffer = 1} ; Import-Module @params
  • Supports flags and parameters: Import-Module -PassThru PSReadLine
  • Can be called almost everywhere: function Load {Import-Module PSReadLine}

Therefore, it is well suited for ad-hoc module loading and dynamic reloading.

using module

using is a keyword, so it's not something you can pass around like Import-Module. It doesn't take parameters the same way as cmdlets do, and it does not work with pipelines. In short, it's a primitive. Yet another limitation is that it has to be placed on top of the script, before all other statements.

A case when you need to use using module is when you want to load classes and enums. Neither Import-Module nor #Requires will add classes defined in a module into your scope. Generally speaking, it's designed for casual module loading.

#Requires -Modules

This is used to assert that certain modules are loaded (amongst others). In contrast to the rest, this command fails if the module cannot be loaded with Import-Module. Another difference is that it works only in scripts -- it does nothing in shell.

like image 69
radrow Avatar answered Feb 28 '26 06:02

radrow