I need to run a powershell script which queries the MongoDB collection from pipeline. I am using latest MongoDB driver 2.9.3. I wrote the script as below -
$Assem = ("D:\PoweshellMongoDB\Drivers\MongoDB.Bson.dll", "D:\PoweshellMongoDB\Drivers\MongoDB.Driver.dll", "D:\PoweshellMongoDB\Drivers\MongoDB.Driver.Core.dll")
$Source = @"
using MongoDB.Bson;
using MongoDB.Driver;
using System;
namespace MongoDBSample
{
public static class MongoRepository
{
public static void Connect()
{
try
{
var mongoClient = new MongoClient("mongodb://localhost:27017");
var database = mongoClient.GetDatabase("ILP4");
var collection = database.GetCollection<BsonDocument>("Issues");
var count = collection.CountDocumentsAsync(new BsonDocument()).ConfigureAwait(false);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
"@
Add-Type -ReferencedAssemblies $Assem -TypeDefinition $Source -Language CSharp
[MongoDBSample.MongoRepository]::Connect()
But when I debug the script I am getting below error -
Exception calling "Connect" with "0" argument(s): "Could not load file or assembly 'MongoDB.Driver, Version=2.9.3.0, Culture=neutral, PublicKeyToken=null' or
one of its dependencies. The system cannot find the file specified."
At D:\PoweshellMongoDB\PowerMongo.ps1:34 char:1
+ [MongoDBSample.MongoRepository]::Connect()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : FileNotFoundException
I am not sure which reference I am missing. Is there a better way of doing it? Or do I need to update the driver to older version? Please advise.
I found the solution. I created a .NET Framework class library which connects to MongoDB using MongoDB driver 2.3.1. In my pipeline I created setup as - checkout library code from source control, build and publish the dll, from my inline powershell script I am referring this dll and executing it.