Fred
Fred

Reputation: 4076

reference assembly in Powershell script

In Visual Studio I'm able to simply add a reference to an assembly, for example: Interop.ADODB.

How do I do this in powershell? The following is exploding

[Reflection.Assembly]::LoadWithPartialName("Interop.ADODB")

$conn = New-Object ADODB.Connection

And here is the error message

New-Object : Constructor not found. Cannot find an appropriate constructor for type ADODB.Connection.
At C:\Users\michaelr\Desktop\jet-project\PS\test.ps1:3 char:19
+ $conn = New-Object <<<<  ADODB.Connection
    + CategoryInfo          : ObjectNotFound: (:) [New-Object], PSArgumentException
    + FullyQualifiedErrorId : CannotFindAppropriateCtor,Microsoft.PowerShell.Commands.NewObjectCommand

I'm on Windows 7 x64.

Upvotes: 0

Views: 2710

Answers (3)

x0n
x0n

Reputation: 52420

The answer's right in front of you:

Cannot find an appropriate constructor for type ADODB.Connection

You need to pass the connection string to the constructor like this:

$c = new-object ADODB.connection "server=foo;user id=bar ..."

However, I don't understand why you want to use 1998-era ADODB in .NET when you can use System.Data instead. Check out this MSDN article on accessing databases with PowerShell:

http://technet.microsoft.com/en-us/magazine/hh855069.aspx

Upvotes: 0

Andrew Savinykh
Andrew Savinykh

Reputation: 26280

Use this line instead:

$conn = New-Object -comobject ADODB.Connection

Powershell understand com object natively (well to the extent it's possible for objects that don't always have a lot of metadata) and does all the interop for you. You just need to tell powershell that it's a COM object. You don't need to reference the interop assemblies explicitly.

Having said that, depending on your task you might be better off using a native .net provider instead of ADODB.

Upvotes: 2

mikekol
mikekol

Reputation: 1862

You're looking for the Add-Type cmdlet, which lets you either compile .NET code into an in-memory assembly, or load an assembly from disk.

Check out the -AssemblyName parameter if you want to load an assembly from the GAC, or the -Path parameter if you know exactly where the DLL you want to load is.

Upvotes: 0

Related Questions