【发布时间】:2018-12-15 05:29:16
【问题描述】:
我正在尝试遍历仅包含 xml 文件的特定文件目录,并替换每个文件中特定定义的节点。我现在的问题是文件路径被定义为 c:\users\myusername\filepath 而不是坚持脚本中定义的原始文件路径。这发生在我的 $xml 分配期间,因为 $filepath 变量对于脚本中的其他命令正常工作。我不能在这里使用 Get-Content 吗?我的印象是 get-content 应该可以工作,因为它一次编辑 1 个文件。
当前代码:
#updating xml and not including sub-directories
$filepath = "\\server1\SP\ConsensusModeling" #folder with multiple xml files, this is NOT located in my \users\ folder.
Foreach($file in Get-ChildItem $filePath | where {!$_.PSIsContainer}){
$xml = [xml](Get-Content $file)
#updating attributes at each node
$node = $xml.ConsensusModelingConfig #location of internal node tree
$node.APPServer = "server1"
$node.APPDB = "ConsensusModelingAPP"
$node.SSASServer = "server1SSAS"
$node.SSASDB = "ConsensusModelingDB"
$xml.Save($filePath)
}
我正在尝试编辑的文件夹中的文件示例/我正在尝试创建的结果。这些当前是不同的值,我想将它们设置为以下值。其中有 4 个。 ConsensusModeling.xml:
<ConsensusModelingConfig>
<APPServer>Server1</APPServer>
<APPDB>ConsensusModelingAPP</APPDB>
<SSASServer>Server1SSAS</SSASServer>
<SSASDB>ConsensusModelingDB</SSASDB>
</ConsensusModelingConfig>
错误信息:
Get-Content : Cannot find path 'C:\Users\myusername\mytestfile
At \\scriptlocation.ps1:628 c
+ $xml = [xml](Get-Content $file)
+ ~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound:
(C:\Users\Alex.p...eling_Score.xml:String) [G
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetContentCommand
根据错误消息,我的路径被分配给 C:\users 等,而不是保留在 $filepath 变量中定义的原始文件路径。这是为什么呢?
解决方案: 根据@mklement0 的评论,以下代码修复了我的问题,现在所有文件的属性都已正确更新。
#updating xml and not including sub-directories
$filepath = "\\server1\SP\ConsensusModeling" #folder with multiple xml files, this is NOT located in my \users\ folder.
Foreach($file in Get-ChildItem $filePath | where {!$_.PSIsContainer}){
$xml = [xml](Get-Content $file.FullName)
#updating attributes at each node
$node = $xml.ConsensusModelingConfig #location of internal node tree
$node.APPServer = "server1"
$node.APPDB = "ConsensusModelingAPP"
$node.SSASServer = "server1SSAS"
$node.SSASDB = "ConsensusModelingDB"
$xml.Save($file.FullName)
}
【问题讨论】:
-
使用PSv3+时建议改成:
Foreach($file in (Get-ChildItem "$filePath\*.xml" -File)){ -
$file字符串化为 仅仅是文件名,而不是完整路径,因为使用了Get-ChildItem命令的细节 - 有关详细信息,请参阅链接帖子。使用$file.FullName是一种简单的解决方法。
标签: xml powershell