简体   繁体   English

如何使用 PowerShell 从 Connectionstring 获取数据源?

[英]How to get datasource from Connectionstring using PowerShell?

In .Net we can get the datasource from a connectionstring using below mechanism:在 .Net 中,我们可以使用以下机制从连接字符串中获取数据源:

System.Data.SqlClient.SqlConnectionStringBuilder builder = new System.Data.SqlClient.SqlConnectionStringBuilder(connectionString);

string server = builder.DataSource;

I was trying to do that in PowerShell but getting the following exception:我试图在 PowerShell 中执行此操作,但出现以下异常:

$ConstringObj = New-Object System.Data.SqlClient.SqlConnectionStringBuilder($conString)

New-Object : Exception calling ".ctor" with "1" argument(s): "Keyword not supported: 'metadata'."新对象:使用“1”参数调用“.ctor”的异常:“不支持关键字:‘元数据’。” At line:1 char:17 + $ConstringObj = New-Object System.Data.SqlClient.SqlConnectionStringBuilder($con ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [New-Object], MethodInvocationException + FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand在 line:1 char:17 + $ConstringObj = New-Object System.Data.SqlClient.SqlConnectionStringBuilder($con ... + ~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [新对象], MethodInvocationException +fullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand

How to do that in PowerShell?如何在 PowerShell 中做到这一点?

Problem问题

There's some weird behavior when using SqlConnectionStringBuilder in PowerShell - let me explain在 PowerShell 中使用SqlConnectionStringBuilder时有一些奇怪的行为 - 让我解释一下

Since it's a dotnet class, you'd expect all of the same properties and methods available in C#由于它是一个 dotnet 类,因此您会期望 C# 中可用的所有相同的属性和方法

For example, this works fine in C#:例如,这在 C# 中工作正常:

var cnnBuilder = new SqlConnectionStringBuilder();
cnnBuilder.DataSource = "server_name";
cnnBuilder.InitialCatalog = "db_name";

So the equivalent code in PS, should work:所以 PS 中的等效代码应该可以工作:

$cnnBuilder = New-Object System.Data.SqlClient.SqlConnectionStringBuilder
$cnnBuilder.DataSource = "server_name"
$cnnBuilder.InitialCatalog = "db_name"

However, SqlConnectionStringBuilder is built ontop of DbConnectionStringBuilder which implements IDictionary so fundamentally we're working with a dictionary object that has some syntactic sugar wrappers然而, SqlConnectionStringBuilder是建立在DbConnectionStringBuilder之上的,它实现了IDictionary所以从根本上我们正在使用一个具有一些语法糖包装器的字典对象

.NET resolves this with an override on the dictionary accessors and setters like this (simplified here): .NET 通过覆盖字典访问器和 setter 来解决这个问题(此处简化):

public override object this[string keyword] {
    get {
        Keywords index = GetIndex(keyword);
        return GetAt(index);
    }
    set {
        Keywords index = GetIndex(keyword);
        switch(index) {
            case Keywords.DataSource: DataSource = ConvertToString(value); break;
            case Keywords.InitialCatalog: InitialCatalog = ConvertToString(value); break;
            // ***
        }
    }
}

So really, it's taking the DataSource property and mapping it to the "Data Source" key ( with space )所以真的,它采用DataSource属性并将其映射到"Data Source"带空格

Whenever PS assigns or retrieves a value, it has to decide whether to use the underlying dictionary implementation or the property.每当 PS 分配或检索值时,它必须决定是使用底层字典实现还是使用属性。 And when you look for DataSource in the dictionary (without the space), that sql connection keyword doesn't exist.当您在字典中查找DataSource时(没有空格),该sql 连接关键字不存在。

Solutions解决方案

Opt 1 - Use Dictionary Names选项 1 - 使用字典名称

You can use the bracket or dot notation with the actual sql key to access the entry in the hashtable您可以使用括号或点符号和实际的 sql 键来访问哈希表中的条目

$cnnBuilder = New-Object System.Data.SqlClient.SqlConnectionStringBuilder
$cnnBuilder["Data Source"] = "server_name"
$cnnBuilder."Initial Catalog" = "db_name"

Opt 2 - Use PSBase选项 2 - 使用PSBase

PSBase returns the "raw view of the object" and will give us the default behavior in dotnet PSBase返回“对象的原始视图” ,并将为我们提供 dotnet 中的默认行为

$cnnBuilder  = New-Object System.Data.SqlClient.SqlConnectionStringBuilder
$cnnBuilder.PSBase.DataSource = "server_name"
$cnnBuilder.PSBase.InitialCatalog = "db_name"

Opt 3 - Use -Property Parameter选项 3 - 使用-Property参数

During the construction, you can set the -Property parameter on New-Object which "sets property values and invokes methods of the new object."在构建过程中,您可以在New-Object上设置-Property参数,该参数“设置属性值并调用新对象的方法”。

$cnnBuilder  = New-Object System.Data.SqlClient.SqlConnectionStringBuilder `
    -Property @{
        DataSource = "server_name"
        InitialCatalog = "db_name"
    }

Additional Reading补充阅读

Using SQLConnection object in PowerShell在 PowerShell 中使用 SQLConnection 对象

Your example should work.你的例子应该有效。 However, you could also grab the datasource using a regex:但是,您也可以使用正则表达式获取数据源:

[regex]::Match($ConstringObj, 'Data Source=([^;]+)').Groups[1].Value

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM