【问题标题】:How to get Database Name from Connectionstring in PowerShell如何从 PowerShell 中的 Connectionstring 获取数据库名称
【发布时间】:2017-01-26 15:11:03
【问题描述】:

我正在尝试从 PowerShell 中的连接字符串中获取数据库名称。

"Server=server\instance;uid=User;pwd=Hello;Database=SomeName;"

我可以想到两种方法来做到这一点,要么搜索字符串Database,直到第一个;,然后拆分=上的字符串并选择数据库名称——但我真的不知道知道该怎么做。

第二种方式可以使用DBConnectionStringBuilder,如下所示:

$sb = New-Object System.Data.Common.DbConnectionStringBuilder
$sb.set_ConnectionString($cstring)
[string]$Database = ($sb | ? {$_.Keys -eq 'Database'}).value

但是通过这种方式,无论我如何尝试过滤数据库名称,它都不会给我返回的数据库名称。

问题:从连接字符串中获取我的 Databasename 的最佳方法是什么?

【问题讨论】:

    标签: powershell


    【解决方案1】:

    使用第二种方法,但要简化:

    $cstring = "Server=server\instance;uid=User;pwd=Hello;Database=SomeName;"
    
    $sb = New-Object System.Data.Common.DbConnectionStringBuilder
    $sb.set_ConnectionString($cstring)
    $Database = $sb.database
    

    这很好用。

    如果你想在key不存在的情况下避免出错,有很多方法可以做到这一点,更惯用的方法是先查找key:

    if ($sb.HasKey('Database')) {
        $Database = $sb.Database
    }
    

    或者对象自己的TryGetValue方法:

    if ($sb.TryGetValue('Database', [ref] $Database)) {
        # It was successful
        # $Database already contains the value, you can use it.
    } else {
        # The key didn't exist.
    }
    

    字符串解析

    我不推荐在这种情况下使用这些,因为数据库连接字符串格式具有一定的灵活性,以及​​为什么要让您的代码了解所有可能性并在该代码已经编写时尝试正确处理它们(对象你在上面使用)?

    但为了完整起见,我会通过拆分和正则表达式匹配和捕获来做到这一点:

    $cstring -split '\s*;\s*' |
        ForEach-Object -Process {
            if ($_ -imatch '^Database=(?<dbname>.+)$') {
                $Database = $Matches.dbname
            }
        }
    

    所以在这里我首先拆分一个分号;,周围有任意数量的空格。然后将每个元素(应该只是键值对)与另一个正则表达式进行检查,专门寻找Database=,然后在名为dbname 的命名捕获组中捕获之后的内容,直到字符串结尾。如果匹配成功,则将捕获组的结果赋值给变量。

    如果存在,我仍然更喜欢合适的解析器。

    【讨论】:

      【解决方案2】:

      试试这个

      "Server=server\instance;uid=User;pwd=Hello;Database=SomeName;".split(";") | 
                  %{[pscustomobject]@{Property=$_.Split("=")[0];Value=$_.Split("=")[1]}} |
                          where Property -eq "Database" | select Value
      

      【讨论】:

        【解决方案3】:

        其他解决方案

        $template=@"
        {Property*:Abc123}={Value:Test123}
        {Property*:Def}={Value:XX}
        "@
        
        "Server=server\instance;uid=User;pwd=Hello;Database=SomeName;".replace(";", "`r`n") | ConvertFrom-String -TemplateContent $template |
        where Property -eq "Database" | select Value
        

        【讨论】:

          猜你喜欢
          • 2017-06-09
          • 2014-03-29
          • 2011-10-30
          • 2023-04-09
          • 1970-01-01
          • 1970-01-01
          • 2018-10-12
          • 2015-11-23
          • 2014-07-03
          相关资源
          最近更新 更多