开发者

Importing modules -ascustomobject and module parameters in PowerShell

Given the following modules开发者_如何学C:

adonetlib.psml

param($ModelModule)

$dbmodel=import-module $ModelModule -AsCustomObject 

function new-ADOnetconnection{
   return $dbmodel.newconnection()
}

mysqlmodel.psm1

function newconnection{
   write-host "MySQL connection"
}

sqlservermodel.psm1

function newconnection{
   write-host "SQLServer connection"
}

I'd like to be able to do this:

$mysql= import-module adonetlib -argumentlist mysqlmodel -ascustomobject
$sqlserver= import-module adonetlib -argumentlist sqlservermodel -ascustomobject

and have the following be true (sorry about the syntax):

$mysql."new-adonetconnection"() -> returns "MySql connection"
$sqlsever."new-adonetconnection"() -> returns "SQLServer connection"

Apparently, though, the adonetlib module is only loaded once (even though we imported it with different arguments). Both statements return "MySQL connection".

Also,

get-module -all 

shows that the mysqlmodel module is loaded, but sqlservermodel isn't.

Any ideas about how I can get this to work?


The functionality you're looking for may be present already in the Powershell Community Extensions:

PS C:\Users\davidp> Get-command -Module pscx | ? { $_ -like "*-ado*" } | select name

Name
----
Get-ADObject
Get-AdoConnection
Get-AdoDataProvider
Invoke-AdoCommand

But in case you're implementing just for fun:

You might be better off using submodules to implement the polymorphic behavior it looks like you're trying to achieve. The top-level module would export a single New-ADOnetConnection cmdlet, with a parameter to select which DB you want to use for that connection; then it would dynamically choose which submodule to use to carry out the command.

If you'd like to avoid having to specify the DB on every call, you could create your own preference variable.


Try Import-Module -Force in your script. For some reason, the command doesn't replace any previous import without it

-Force Re-imports a module and its members, even if the module or its members have an access mode of read-only.

Edit: Sorry, missed the comment above. No intention of "stealing" the answer ;)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜