powershell-遍历xml文件的文件目录,并为每个文件替换特定的节点

时间:2018-12-14 18:01:03

标签: xml powershell

我试图遍历仅包含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)

            }

1 个答案:

答案 0 :(得分:0)

您是否从c:\ users ...运行脚本?

这是您可以做的事情:

$filepath = "\\server1\SP\ConsensusModeling"
Get-ChildItem $filePath | % {

        $XML = import-clixml $_.FullName #this will get you the childitem full path.
        #
        #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)


}