问题描述
我想使用 Powershell 更改 web.config
文件中连接字符串的一部分.
我可以使用以下代码读取所需的连接字符串:
[
并提取正确的值:
服务器=testDB01\sql14;uid=abc;pwd=def;database=ghi;language=english现在我想更改="之后的部分以根据需要调整值.我可以通过将文本分成部分来访问这些值,例如
$ConString.Split(";")[0].Split("\")[1]
返回
sql14我现在如何更改该值并将其保存到文件中?
这是一个使用 -replace
运算符 来替换连接字符串中的数据库名称:
注意:
正如 Ansgar Wiechers 在评论中指出的那样,点符号 深入到 $)很方便,但有局限性:它不适合对 结构性更改.
- 要执行结构更改,您必须直接使用基础[-derived] 类型.
但是,对于简单的非结构性更改(包括这种情况),点表示法可用于进行更新,即:
- 更改 leaf 元素的文本内容.
- 更改属性(层次结构中的任何位置)的值 - 如本例所示.
点表示法的一个普遍缺陷是可能与基础类型的成员发生名称冲突 - 请参阅这个答案.
# 创建一个示例
以上产生以下结果 - 注意 sql14
是如何被 sql999
替换的:
<配置><连接字符串><connectionString server="server=testDB01\sql999;uid=abc;pwd=def;database=ghi;language=english"/><connectionString server="..."/></添加></connectionStrings></配置>
I want to change a part of a connection string within an web.config
file with Powershell.
I can read the desired connection string with the following code:
[
and get the proper value extracted:
server=testDB01\sql14;uid=abc;pwd=def;database=ghi;language=english
Now I want to change the parts after the "=" to adapt the values as needed.I can access the values by spliting the text into part with e.g.
$ConString.Split(";")[0].Split("\")[1]
that returns
sql14
How can I now change that value and save it to the file?
Here's a self-contained example that uses the -replace
operator to replace the database name in your connection string:
Note:
As Ansgar Wiechers points out in a comment, dot notation to drill into an $) is convenient, but has limitations: it isn't suited to making structural changes to
- To perform structural changes, you must work directly with the methods of the underlying [-derived] types.
However, for simple, non-structural changes (which includes this case), dot notation can be used to make updates, namely:
- Changing the text content of a leaf element.
- Changing the value of an attribute (anywhere in the hierarchy) - as in this case.
A general pitfall with dot notation is the potential for name collisions with the members of the underlying types - see this answer.
# Create a sample
The above yields the following - note how sql14
was replaced with sql999
:
<?
这篇关于更改属性值的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!