Question

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?

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top