【问题标题】:Powershell regex for connectionStrings?用于连接字符串的 Powershell 正则表达式?
【发布时间】:2011-11-28 16:39:18
【问题描述】:

由于某种原因,我在解析 web.config 文件中的连接字符串时遇到了麻烦。

我已经得到了 connectionString 但我正在尝试获取所有值,例如

  • 数据源
  • 初始目录
  • 用户名
  • 等等……

连接字符串如下所示:

数据源=db.sample.com;用户 id=sample-user;password=sample-password;初始 目录=样本目录;

【问题讨论】:

  • 您需要使用正则表达式吗?看起来对 Powershell 用于拆分字符串的任何方法的两次调用都可以解决问题。在; 上调用一次拆分,然后遍历结果并按= 拆分以获取您的键/值对。我会将此作为答案,但我不知道 a) Powershell 是否具有拆分功能,以及 b) 它叫什么。
  • 是的,效果很好!谢谢!

标签: regex string parsing powershell connection


【解决方案1】:

使用System.Data.Common.DbConnectionStringBuilder

$sb = New-Object System.Data.Common.DbConnectionStringBuilder

# Attempting to set the ConnectionString property directly won't work, see below
$sb.set_ConnectionString('Data Source=db.sample.com;user id=sample-user;password=sample-password;Initial Catalog=sample-catalog;')

$sb

输出:

Key             Value          
---             -----          
data source     db.sample.com  
user id         sample-user    
password        sample-password
initial catalog sample-catalog 

更多详情请参见:DbConnectionStringBuilder does not parse when used in PowerShell

(这就是为什么使用这种有趣的语法$sb.set_ConnectionString(...) 而不是$sb.ConnectionString = ...)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-17
    • 2014-06-24
    • 2013-11-19
    • 2015-03-05
    • 2022-01-25
    • 2012-05-26
    • 1970-01-01
    相关资源
    最近更新 更多