开发者

Add-pssnapin from a function in a module does not work (scope issue?)

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 snapi开发者_开发问答n 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?


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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜