How to import the npgsql module?

試著忘記壹切 提交于 2019-12-12 16:10:46

问题


I need to connect to a PostgreSQL database from within PowerShell scripts. But how to install npgsql WITHOUT VisualStudio? There is no nuget!

So I tried to install the driver in the GAC using the newest MSI file (Npgsql-3.0.5.msi).

Using gacutil.exe shows, that it is installed:

Npgsql, Version=3.0.5.0, Culture=neutral, PublicKeyToken=5d8b90d52f46fda7, processorArchitecture=MSIL

But PowerShell does not know anything about it! Get-Module -ListAvailable should show it but:

PS C:\WINDOWS\system32> (gmo -l n*).Name

NetAdapter  
NetConnection  
NetEventPacketCapture  
NetLbfo  
NetNat  
NetQos  
NetSecurity  
NetSwitchTeam  
NetTCPIP  
NetWNV  
NetworkConnectivityStatus  
NetworkLoadBalancingClusters  
NetworkTransition  
NFS  
PS C:\WINDOWS\system32> _

There is no module Npgsql!

I was searching for Npgsql.dll and it is there:

PS  C:\Windows\Microsoft.NET\assembly\GAC_MSIL\Npgsql\v4.0_3.0.5.0__5d8b90d52f46fda7> dir

Verzeichnis: C:\Windows\Microsoft.NET\assembly\GAC_MSIL\Npgsql\v4.0_3.0.5.0__5d8b90d52f46fda7


Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---        08.01.2016     08:10     446464 Npgsql.dll


PS C:\Windows\Microsoft.NET\assembly\GAC_MSIL\Npgsql\v4.0_3.0.5.0__5d8b90d52f46fda7> _

Because of the not recognised module npgsql my PowerShell code does not work:

function getDBConnection ($MyDBServer, $MyDBPort, $MyDatabase, $MyUid, $MyPwd) {
  $DBConnectionString = "Provider=PostgreSQL OLE DB Provider;Data Source=$MyDBServer;location=$MyDatabase;User ID=$MyUid;password=$MyPwd;timeout=1000;"
  $DBConn = New-Object System.Data.OleDb.OleDbConnection;
  $DBConn.ConnectionString = $DBConnectionString
  try {
    $DBConn.Open
  } catch {
    "Failed to connect! Error: "+ $_.Exception.Message
  }

  return $DBConn
}

function closeDBConnection ($DBConn) {
  $DBConn.Close
}

$query = "select * from test_table1"
$MyDBConnection = getDBConnection "dbserver" 5432 "databasename" "user" "pass"

try {
  $cmd = New-Object System.Data.OleDb.OleDbCommand($query, $MyDBConnection)
} catch {
  "Failed to create command object! Error: " + $_.Exception.Message
}
...

The $DBConn.Open doesn't fail, but the property ConnectionState remains Closed after the Open call.

The creation of an instance of OleDbCommand crashes with a german error message:

Failed to create command object! Error: Für "OleDbCommand" und die folgende Argumenteanzahl kann keine Überladung gefunden werden: "2".

It means that there are no overloaded methods with two parameters.

QUESTIONS:

  • What do I need to install/configure so that Npgsql is visible in PowerShell?
  • How do I load/import the Npgsql module in a PowerShell script or module?

回答1:


When in doubt, read the documentation. Get-Module -ListAvailable only lists modules from the directories listed in $env:PSModulePath.

-ListAvailable

Gets all installed modules. Get-Module gets modules in paths listed in the PSModulePath environment variable. Without this parameter, Get-Module gets only the modules that are both listed in the PSModulePath environment variable, and that are loaded in the current session. ListAvailable does not return information about modules that are not found in the PSModulePath environment variable, even if those modules are loaded in the current session.

However, you can simply import any module with its full path in your script:

Import-Module 'C:\Windows\Microsoft.NET\assembly\GAC_MSIL\Npgsql\v4.0_3.0.5.0__5d8b90d52f46fda7\Npgsql.dll'

Using wildcards in the path is allowed:

Import-Module 'C:\Windows\Microsoft.NET\assembly\GAC_MSIL\Npgsql\*\Npgsql.dll'

If you want to be able to load the module by name create a subfolder Npgsql in one of the directories listed in $env:PSModulePath and put the DLL into that subfolder.




回答2:


Ok, solved it! Here the solution:

Using Windows 8.1 with several .NET versions up to version 4.5 we can use Npgsql 3.0.5.

  1. Download Npgsql-3.0.5.msi from the npgsql website and run the installer
  2. Search for a DLL named 'Npgsql.ll'
  3. Copy this dll to your local project directory (where you have your powershell script)
  4. In the script Load the DLL using Add-Type -Path ".\Npgsql.dll"
  5. Now you are ready to go!

Here some sample code where I connected to a PostgreSQL server running on a remote CentOS server:

Add-Type -Path ".\Npgsql.dll"

function getDBConnection ($MyDBServer, $MyDBPort, $MyDatabase, $MyUid, $MyPwd) {
$DBConnectionString = "server=$MyDBServer;port=$MyDBPort;user id=$MyUid;password=$MyPwd;database=$MyDatabase;pooling=false"
$DBConn = New-Object Npgsql.NpgsqlConnection;
$DBConn.ConnectionString = $DBConnectionString
$DBConn.Open()

return $DBConn
}

function closeDBConnection ($DBConn)
{
    $DBConn.Close
}

$MyDBConnection = getDBConnection "db.mydomain.com" 5432 "databasename" "username" "password"
$query = "SELECT * FROM test_table1;"
$DBCmd = $MyDBConnection.CreateCommand()
$DBCmd.CommandText = $query
$adapter = New-Object -TypeName Npgsql.NpgsqlDataAdapter $DBCmd
$dataset = New-Object -TypeName System.Data.DataSet
$adapter.Fill($dataset)
$dataset.Tables[0]
closeDBConnection($MyDBConnection)
.....

npgsql seems to be compatible with System.Data.OleDb. So the OleDb documentation on technet.microsoft.com can be used as a reference.




回答3:


Its probably a bit late but here is how Npgsql Version 4.0.2 can be included in powershell on Windows 10

  1. Register the packagesource NuGet with: register-PackageSource -provider NuGet -name nugetRepository -location http://www.nuget.org/api/v2

  2. In a powershell console with Administrator rights enter the command: Find-Package Npgsql | Install-Package positively answer the security questions

3. Enter:

Get-Package Npgsql

and you will see the newly installed package Npgsql /




回答4:


I didn't want to install MSI and had a hard time to add Npgsql.dll from nuget package. It has dependencies from other assemblies, I was trying to collect them separately, but got different kind of errors while adding them.

The solution was to build assemblies using their repo on git hub. It worked on Win10 and then I was able to use same assemblies on win 2012.

Clone or download/unzip the repo: https://github.com/npgsql/npgsql

Open Npgsql.sln with Visual Studio, then build/build solution (might see some errors, ignore)

Then copy dlls from repofolder\npgsql\src\Npgsql\bin\Debug\net452 to your PS project

Then use snippet below to add all these assemblies:

$bin = "C:\folder\with\DLLs"

Add-Type -Path "$bin\Npgsql.dll" -ReferencedAssemblies "$bin\System.*.dll"

$str =  "Server=yourserver;Port=1521;Username=user;Password=pass;Database=somedb"

$conn = New-Object Npgsql.NpgsqlConnection $str 

$conn.Open()


来源:https://stackoverflow.com/questions/34674761/how-to-import-the-npgsql-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!