Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Powershell Snapin for Powershell Module and Import Multiple Times

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?

like image 814
Blake Blackwell Avatar asked Oct 03 '22 12:10

Blake Blackwell


1 Answers

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

like image 104
Lars Truijens Avatar answered Oct 13 '22 10:10

Lars Truijens