DbConnectionStringBuilder 在 PowerShell 中使用时不解析 [英] DbConnectionStringBuilder does not parse when used in PowerShell
问题描述
我正在尝试使用 DbConnectionStringBuilder
的功能来解析类似连接字符串的用户输入.这在 C# 中工作得很好:
I am trying to use capabilities of DbConnectionStringBuilder
for parsing connection-string-like user input. This works just fine in C#:
using System;
using System.Data.Common;
class Program
{
static void Main(string[] args)
{
var sb = new DbConnectionStringBuilder();
sb.ConnectionString = "server = 'smtp.gmail.com'; port = 587; user = you@gmail.com";
Console.WriteLine(sb["server"]);
Console.WriteLine(sb["port"]);
Console.WriteLine(sb["user"]);
}
}
输出:
smtp.gmail.com
587
you@gmail.com
但它在 PowerShell 中不起作用.也就是说,这个字面翻译的 PowerShell 代码
But it does not work in PowerShell. Namely, this literally translated code in PowerShell
$sb = New-Object System.Data.Common.DbConnectionStringBuilder
$sb.ConnectionString = "server = 'smtp.gmail.com'; port = 587; user = you@gmail.com"
$sb["server"]
$sb["port"]
$sb["user"]
根本不产生任何输出.
有什么想法吗?如何使 DbConnectionStringBuilder
在 PowerShell 中用作解析器?
Any ideas why? How to make DbConnectionStringBuilder
to work as a parser in PowerShell?
推荐答案
System.Data.Common.DbConnectionStringBuilder
实现了 IDictionary
.Powershell 有一个使用 .
的字典简写,它允许检索和分配键/值对,就像键是一个属性一样:
System.Data.Common.DbConnectionStringBuilder
implements IDictionary
. Powershell has a shorthand for dictionaries using .
that allows retrieval and assignment of key/value pairs as if the key was a property:
$dict = @{}
$dict["key1"] = 'value1'
$dict.key2 = 'value2'
您可以看到它将整个连接字符串存储为键/值对,而不是以这种方式存储在 ConnectionString
属性上:
You can see that it is storing the entire connection string as a key/value pair instead of on the ConnectionString
property this way:
$sb = New-Object System.Data.Common.DbConnectionStringBuilder
$sb.ConnectionString = "server = 'smtp.gmail.com'; port = 587; user = you@gmail.com"
$sb #formatted table of key/value pairs
解决这个问题的最简单方法是调用为属性生成的 set_
/get_
方法:
The easiest way to get around this is to call the set_
/get_
methods generated for properties:
$sb = New-Object System.Data.Common.DbConnectionStringBuilder
$sb.set_ConnectionString("server = 'smtp.gmail.com'; port = 587; user = you@gmail.com")
$sb["server"]
$sb["port"]
$sb["user"]
这篇关于DbConnectionStringBuilder 在 PowerShell 中使用时不解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!