我正在使用powershell的XML功能来修改.config文件.除非我提供完整的路径名,否则调用XMLDocument.Save没有任何效果.
# Open the xml file
$config = [xml](get-content web.config)
#
# modify the XML
$config.SelectNodes("./configuration/connectionStrings/add[@name='LocalSqlServer']") | % { $connNode = $_ }
$connNode.connectionString = $connNode.connectionString -replace '^(.*)Server=[^;]+(.*)$', '$1Server=192.168.5.2$2'
#
#
# Now I save it again
#
# This doesn't save it!
$config.Save("web.config");
# However, this works
$config.Save("{0}\\web.config" -f (get-location));
Run Code Online (Sandbox Code Playgroud)
为什么$ config.Save("web.config")不起作用?
除了本地目录以外,我最终还是将它保存在其他地方吗?
Jam*_*mes 66
原因是powershell中的当前工作目录不一定与进程工作目录相同.
这是因为powershell工作方向(Get-Location)可以使用不同的文件系统提供程序 - 例如注册表或证书.另外因为powershell可以有多个运行空间,每个运行空间都可以拥有自己的当前工作目录.
有两种解决方法.
一种是使用Resolve-Path (Resolve-Path "orders.xml"),虽然这将在返回值之前检查存在,因此对于新文件的创建,这可能是一个问题.另一种选择是使用get-location的别名:$pwd
例如("$pwd\orders.xml")
因此,对于您的示例,您可以将第2行更改为
$config = [xml](get-content (Resolve-Path "web.config"))
Run Code Online (Sandbox Code Playgroud)
要么
$config = [xml](get-content "$pwd\web.config")
Run Code Online (Sandbox Code Playgroud)
并且分别是第12行
$config.Save((Resolve-Path "web.config"));
Run Code Online (Sandbox Code Playgroud)
要么
$config.Save("$pwd\web.config");
Run Code Online (Sandbox Code Playgroud)
mjo*_*nor 26
如果它没有进入当前的工作目录,我会检查$ home.
| 归档时间: |
|
| 查看次数: |
31510 次 |
| 最近记录: |