解析 XML 并重命名文件名中的特殊字符(XML 和位置)

Parse XML and rename special char in filename (both XML and location)

我正处于将文件从 Unix 复制到 Windows 的情况。 Unix 中的文件具有 Windows 不接受的特殊字符。

我有一个 XML 文件,其中包含位置中每个文件的标签。此 XML 文件将在其中一个应用程序中传递以进行处理。

  1. 选择一个 XML 文件。
  2. 通读属性并找到 <file>
  3. 检查属性值是否有特殊字符。
  4. 如果没有特殊字符则转到下一个文件。如果该值具有特殊字符 - 转到该位置并使用有效字符重命名特殊字符(例如,将 / 重命名为 -)。
  5. 在 XML 文件标签中进行相同的重命名。
  6. 转到下一个文件标签并选择下一个 XML 内容。

我正考虑在 PowerShell 中进行。

样本XML:

<import>
    <node type="document" action="create">
        <location>XXXXXX</location>
        <title>log_0.log</title>
        <created>20190117</created>
        <file>\test*\log/0/.log</file>
    </node>

<File> 在上面的示例中有两个特殊字符...一个在文件夹名称 (*) 中,另一个在文件名 (//) 中。

要解决这个问题,请自己改编以下片段。

$x=[xml]@'
<import>
  <node type="document" action="create">
    <location>XXXXXX</location>
    <title>log_0.log</title>
      <created>20190117</created>
      <file>\test*\log/0/.log</file>
  </node>
</import>
'@
$x.SelectNodes('/import/node/file') |
  ForEach-Object {
    $file = $_.'#text'
    [char[]]$file |
      ForEach-Object {
        if( [System.IO.Path]::GetInvalidPathChars() -contains $_ ) {
          $file = $file.Replace($_, '_')
        }
        if( $_ -ne [System.IO.Path]::DirectorySeparatorChar -and
            [System.IO.Path]::GetInvalidFileNameChars() -contains $_ ) {
          $file = $file.Replace($_, '_')
        }
      }
    $file
  }

输出:

\test_\log_0_.log