Using a PowerShell Requires Statement to Efficiently Load PowerCLI Modules

Chris Wahl · Posted on2017-01-172020-05-06

Since the release of PowerShell version 3, the ability to automatically load modules has been an exciting feature for those using the console. Prior to this, getting access to the cmdlets and functions buried inside of a module (or snappin) needed to be explicitly imported. However, not all modules will support this feature. It’s up to the module owner to determine which module commands are exported. To see this, I’ll use the Pester module as an example.

This is why I can type Invoke-Pester from anywhere in the console session and it will autocomplete via Intellisense and subsequently load the Pester module when called. The neat thing is that loading a module isn’t just limited to calling a command. You could also use, for example, the Get-Help cmdlet as shown below. Notice how the first use of Get-Module does not show the Pester module loaded, but after requesting the help file, the Pester module is now loaded. Fairly snazzy.

VMware’s PowerCLI Modules

As stated earlier, not all modules support this. One example is the VMware PowerCLI 6.5 module. I bring this up as I’ve had a number of folks report this behavior to me on various forums and comments threads. My guess is that as VMware continues to swap over from a rigid snappin architecture to a more open module architecture this will be remediated. However, for now there are hardly any commands being exported by any of their modules.

If you’ve ever tried entering Connect-VIServer without first implicitly loading the module, you’ll know the pain of seeing the “The term ‘Connect-VIServer’ is not recognized as the name of a cmdlet, function, script file, or operable program” error. I’m assuming there’s just something not quite right with the export code in their module at this time. Of course, you can always implicitly load the module in your code. Kyle Ruddy describes the process on the VMware PowerCLI blog along with a sample script to update your existing scripts. Kudos for sharing!

The other approach is to use a requires statement.

The Requires Statement

A practice that I highly advise making habit is using a requires statement at the top of your scripts and functions. It’s a handy way to define the requirements necessary for code to execute. Here’s some examples of what can be examined:

For this blog post, I’ve written a tiny sample script to show how to require the VMware module before code will execute without having to lay in extra logic or potentially stumble upon a module that’s already loaded and throw an error.

#requires -Modules VMware.VimAutomation.Core
Write-Host "Loaded!"

What an exciting sample script! Its job in life is to load the VMware.VimAutomation.Core module and then write the word “Loaded!” onto the console. Here’s what happens: