在 powershell 中保存 XML 文件需要完整路径。为什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4822575/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Saving an XML file in powershell requires complete path. Why?
提问by Andrew Shepherd
I am using the XML capabilities of powershell to modify a .config file. Calling XMLDocument.Savedoesn't have any effect, unless I supply the complete path name.
我正在使用 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=[^;]+(.*)$', 'Server=192.168.5.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));
Why doesn't $config.Save("web.config") work?
为什么 $config.Save("web.config") 不起作用?
Did I end up saving it somewhere else, other than my local directory?
我最终是否将它保存在其他地方,而不是我的本地目录?
回答by James
The reason is because the current working directory in powershell isn't necessarly the same as the process working directory.
原因是因为 powershell 中的当前工作目录不一定与进程工作目录相同。
This is because the powershell working direction ( Get-Location) can make use of the different filesystem providers - such as the Registry or Certificates.
Also because powershell can have multiple runspaces, each one can have their own current working directory.
这是因为 powershell 工作方向 ( Get-Location) 可以利用不同的文件系统提供程序 - 例如注册表或证书。也因为 powershell 可以有多个运行空间,每个运行空间都可以有自己的当前工作目录。
There are two workarounds to this.
对此有两种解决方法。
One is to use Resolve-Path(Resolve-Path "orders.xml"), although this will check existence prior to returning the value, so for creation of new files, this may be an issue.
The other option is to use the alias of get-location : $pwdfor instance ("$pwd\orders.xml")
一种是使用Resolve-Path(Resolve-Path "orders.xml"),尽管这会在返回值之前检查是否存在,因此对于创建新文件,这可能是一个问题。另一种选择是使用 get-location 的别名:$pwd例如("$pwd\orders.xml")
So for your example you could either change line 2 to be
因此,对于您的示例,您可以将第 2 行更改为
$config = [xml](get-content (Resolve-Path "web.config"))
or
或者
$config = [xml](get-content "$pwd\web.config")
and respectivly line 12 to be
分别为第 12 行
$config.Save((Resolve-Path "web.config"));
or
或者
$config.Save("$pwd\web.config");
回答by mjolinor
If it didn't go to the current working directory, I'd check $home.
如果它没有转到当前工作目录,我会检查 $home。

