PowerShell function to check for a loaded module

Last week I’ve received a question concerning a check if a PowerShell module is loaded. If it’s not, load it.
Here’s a function I’ve used over the last year in many of my scripts, I hope you find it useful.

9 comments

  1. Nice1… I was in need for something similar for snap-ins (eg Exchange)

    so after a bit rewriting:

    function Check-LoadedSnapIN{
    Param( [parameter(Mandatory = $true)][alias(“SnapIN”)][string]$SnapINName)
    $LoadedModules = Get-PSSnapIn | Select Name
    if (!$LoadedModules -like “*$SnapINName*”) {add-pssnapin $SnapINName}
    }

  2. Jeff Wouters says:

    Hi Bas,
    Glad you like it. If you were to use the -Registered parameter attached to the Get-PSSnapIn cmdlet you’ll get all the registered snapins: Get-PSSnapIn -Registered | Select Name
    Jeff.

  3. but if I where to add the -Registered I would find if it is registered to the machine, but it might not be loaded.

    At least that is what I understand from the technet site.

    I start my scripts for exchange with the add-pssnapin command to have the exchange commandlets.
    So it has to be added to the session…

    This function seemed to do its job… might that be an illusion?? or is it alright as it is?

  4. Jeff Wouters says:

    No illusion, you’re right 🙂

  5. At seems not to be working 🙁 the PSSnapin is not loaded, and it is not in the list.. It is still evaluated as true 🙁

    But I found the following work arround:

    # Deviation from Jeff Wouters function but for PSAddins
    function Check-LoadedSnapIN
    {
    Param( [parameter(Mandatory = $true)][alias(“SnapIN”)][string]$SnapINName)
    if ( (Get-PSSnapin -Name $SnapINName -ErrorAction SilentlyContinue) -eq $null )
    {
    Add-PsSnapin $SnapINName
    }
    }

    And this works as a charm…

Leave a Reply

Your email address will not be published. Required fields are marked *