【问题标题】:Replacing file name in XML by using Get-ChildItem command使用 Get-ChildItem 命令替换 XML 中的文件名
【发布时间】:2015-08-17 13:53:23
【问题描述】:

我正在尝试使用Get-ChildItem 命令替换 XML 中的一些文件名。 XML 中有 6 个文件名,每个文件夹中有 6 个文件。我要做的就是使用 Get-ChildItem 命令替换 XML 中的文件名 如果有帮助,文件名总是递增 1。所以我有以下内容:

Get-ChildItem $dirname\resources\* -filter *.txt -recurse

返回 6 个文件名。当我选择一个 XML 节点时,这也会返回 6 个文件名。

$xml.SelectNodes('//FileName',$XmlNSManager)

如何从Get-ChildItem 命令同步替换 XML 中的每个文件名?即

12341_1.txt --> 100011.txt,
12341_2.txt --> 100012.txt,
12341_3.txt --> 100013.txt,

等等。

【问题讨论】:

    标签: xml powershell-4.0


    【解决方案1】:

    如果我正确理解你的问题,这样的事情应该可以工作:

    $files = Get-ChildItem $dirname\resources\* -Filter *.txt -Recurse |
             select -Expand Name | sort
    
    $i = 0
    $xml.SelectNodes('//FileName', $XmlNSManager) | % {
      $_.'#text' = [string]$files[$i]
      $i++
    }
    

    【讨论】:

    • 这给了我一个错误无法设置“#text”,因为只有字符串可以用作设置 XmlNode 属性的值。在 line:6 char:3 + $_.'#text' = $file[$i] + ~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], SetValueException + FullyQualifiedErrorId : XmlNodeSetShouldBeAString
    • 只是尝试解释一下。 $ xml.SelectNodes( '//文件名',$ XmlNSManager)返回#text ----- 8429006775491_01_01.txt 8429006775491_01_02.txt 8429006775491_01_03.txt 8429006775491_01_04.txt 8429006775491_01_05.txt 8429006775491_01_06.txt我想替换与这些文件的名称$files 的结果 = Get-ChildItem $dirname\resources* -Filter *.txt -Recurse |选择 - 展开名称 |排序
    • @s4ndz 查看更新的答案。另一种方法是将文件名列表定义为字符串数组 ([string[]]$files = Get-ChildItem ...)。不知道为什么需要额外的转换,因为数组元素应该已经是字符串了。
    猜你喜欢
    • 1970-01-01
    • 2017-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-30
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多