Add-pssnapin from function in module does not work (problem with scope?)

I have this function:

function start-sqlsnap { add-pssnapin SqlServerCmdletSnapin100 } 

Regardless of the method used to load the function, get-pssnapin will show the snapin load. But:

  • When pasted into a shell, functions (e.g. invoke-sqlcmd) are recognized
  • If the point is obtained from a file, the functions are recognized.
  • If placed in the psm1 file (inside the module’s folder, in its own folder with the same name as the psm1 file) and loaded using the import module, special snapin functions are not recognized, but running get-pssnapin will show the module is loaded.

Error:

 The term 'invoke-sqlcmd' is not recognized as the name of a cmdlet, function, script file, or operable program. Check t he spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:14 + invoke-sqlcmd <<<< + CategoryInfo : ObjectNotFound: (invoke-sqlcmd:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException 

I tried the same thing with another snapin: Microsoft.EnterpriseManagement.OperationsManager.Client and had the same result. Im working with PowerShell 2 on 2008 R2.

Is this a known bug or feature? Can I solve it somehow?

+4
source share
2 answers

Instead of adding a function to the module file, what if you just add one line:

 add-pssnapin SqlServerCmdletSnapin100 

I tried this and it seemed to work.

+2
source

Adding only one line to your script may be the solution if your function does ONLY one line. But if your functions have many lines, and you need to check some requirements or load another version of PsSnapin depending on the installed version of SQL, this can be problematic.

In this case, the solution creates a PowerShell script file (.ps1) and moves your functions in that file. When you call the function, all included / pssnapins modules will be loaded.

charged pssnapins and modules are NOT available externally:

 Import-Module "MyCustomModule" #(.psm1) 

charged pssnapins and modules are available externally:

 Import-Module "MyCustomModule.ps1 
0
source

All Articles