从Powershell脚本查询Mongo集合

问题描述 投票:0回答:1

我需要运行一个Powershell脚本,该脚本从管道中查询MongoDB集合。我正在使用最新的MongoDB驱动程序2.9.3。我写的脚本如下-

$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()

但是当我调试脚本时,我遇到了以下错误-

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

我不确定我缺少哪个参考。有更好的方法吗?还是需要将驱动程序更新为旧版本?请指教。

mongodb powershell .net-core mongodb-.net-driver
1个回答
0
投票

我找到了解决方案。我创建了一个.NET Framework类库,该库使用MongoDB驱动程序2.3.1连接到MongoDB。在我的管道中,我将安装程序创建为-从源代码管理中签出库代码,构建并发布dll,从我的嵌入式Powershell脚本中引用此dll并执行它。

© www.soinside.com 2019 - 2024. All rights reserved.