4
votes

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 loaded. However:

  1. If pasted in the shell, the functions (like invoke-sqlcmd) are recognized
  2. If dot sourced from a file, the functions are recognized
  3. If placed in a psm1 file (inside the module folder, in its own folder with the same name as the psm1 file) and loaded with import-module, the snapin specific functions are not recognized ā€“ but running get-pssnapin will show the module as 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 a different snapin: Microsoft.EnterpriseManagement.OperationsManager.Client and had the exact same result. Iā€™m running PowerShell 2 on 2008 R2.

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

2
I just tried this and it worked for me What do you get with 'Get-Module'? I get: ModuleType Name ExportedCommands ---------- ---- ---------------- Script sqlps {Invoke-PolicyEvaluation, Invoke-Sqlcmd} ā€“ PeskyGnat

2 Answers

2
votes

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

add-pssnapin SqlServerCmdletSnapin100

I tried that and it seemed to work.

0
votes

Adding only one line to your script can be solution if your function does ONLY one line. But if your functions has a lot of lines and you need to check some requirements or load a different version of PsSnapin depending on the installed SQL version, it can be problematic.

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

charged pssnapins and modules are NOT available from outside:

Import-Module "MyCustomModule" #(.psm1)

charged pssnapins and modules ARE available from outside:

Import-Module "MyCustomModule.ps1