5

I would like to use the SqlServerCmdletSnapin for my custom Powershell Commandlet I am building. If I add the following code to the beginning of my PSM1:

if ( (Get-PSSnapin -Name sqlserverprovidersnapin100 -ErrorAction SilentlyContinue) -eq $null )
{
    Add-PsSnapin sqlserverprovidersnapin100
}

if ( (Get-PSSnapin -Name sqlservercmdletsnapin100 -ErrorAction SilentlyContinue) -eq $null )
{
    Add-PsSnapin sqlservercmdletsnapin100
}
Export-ModuleMember Invoke-SqlCmd

everything works great the first time I run:

Import-Module MyModule -Force

However, the second time I run:

Import-Module MyModule -Force

I get the following error:

Add-PsSnapin : An item with the same key has already been added.

and my code can no longer call Invoke-SqlCmd. What is the best way to add a powershell snapin to my custom module?

4
  • you could try Add-PsSnapin sqlserverprovidersnapin100 -ErrorAction SilentlyContinue Commented Jul 17, 2013 at 22:15
  • 1
    Same issue occurs. The issue seems to be because Import-Module doesn't seem to operate in the same scope as already loaded modules. Not sure why. Commented Jul 18, 2013 at 13:27
  • 3
    If you load a module and then invoke an exported function which calls Add-PSSnapin, the snapin is loaded into the runspace, but the snapin's cmdlets will be directly accessible only to the module script, but not to code outside the module. This gives rise to the behavior above, where if you do a get-pssnapin the snapin won't be listed, but then if you try to add it, you get the above error because technically the snapin has been loaded into the runspace, but not in a way that code outside the module can use it :( Commented Nov 20, 2014 at 15:17
  • 1
    Any solutions/workarounds to this strange behaviour @StephenConnolly? Commented Mar 8, 2017 at 22:07

1 Answer 1

4

You might want to try to specify this module required by your own module through a module manifest (.psd1). See RequiredModules here.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.