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?

Blake Blackwell
  • 7,575
  • 10
  • 50
  • 67
  • you could try `Add-PsSnapin sqlserverprovidersnapin100 -ErrorAction SilentlyContinue` – user1578107 Jul 17 '13 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. – Blake Blackwell Jul 18 '13 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 :( – Stephen Connolly Nov 20 '14 at 15:17
  • 1
    Any solutions/workarounds to this strange behaviour @StephenConnolly? – Murray Rowan Mar 08 '17 at 22:07

1 Answers1

4

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

Lars Truijens
  • 42,837
  • 6
  • 126
  • 143