【问题标题】:Copy files to different locations depending on information from XML file根据 XML 文件中的信息将文件复制到不同的位置
【发布时间】:2015-09-24 13:52:18
【问题描述】:

我确实有以下 XML 文件和文件 file1.txtfile2.txtfile3.txtfile4.txtfile5.txt...

<Oses>
    <OS>
        <Name>Windows 7</Name>
        <Version>6.1</Version>
        <File>file1.txt</File>
        <File>file2.txt</File>
    </OS>
    <OS>
        <Name>Windows Server 2012</Name>
        <Version>6.2</Version>
        <File>file3.txt</File>
        <File>file2.txt</File>
    </OS>
    <OS>
        <Name>Windows Server 2012R2</Name>
        <Version>6.3</Version>
        <File>file4.txt</File>
    </OS>
    <OS>
        <Name>Windows 10</Name>
        <Version>10.0</Version>
        <File>file5.txt</File>
        <File>file6.txt</File>
        <File>file4.txt</File>
    </OS>
</Oses>

我可以像这样使用 PowerShell 读取文档:

[xml]$XmlDocument = Get-Content -Path 'C:\Users\Desktop\New folder\test.xml'

现在的问题是,如何根据操作系统将这些文件复制到 C:\ 内的新文件夹中?根据操作系统的不同,这些文件中的每一个都位于不同的位置并具有不同的名称?

更新:

我已经添加到脚本的开头

New-Item -Type Directory "c:\Windows 7";

New-Item -Type Directory "c:\Windows Server 2012";

这些文件确实会复制到相应的文件夹中,但是我如何使用 xml.xml 中的“版本”字段创建这些文件夹。使用它的值作为文件夹本身的名称?

【问题讨论】:

    标签: xml powershell


    【解决方案1】:

    我建议定义一个将操作系统映射到目标文件夹的哈希表:

    $dst = @{
      'Windows 7'             = 'C:\some\where\win7'
      'Windows Server 2012'   = 'C:\some\where\win2012'
      'Windows Server 2012R2' = 'C:\some\where\win2012r2'
      'Windows 10'            = 'C:\some\where\win10'
    }
    

    然后你可以像这样处理 XML 数据:

    $XmlDocument.Oses.OS | ForEach-Object {
      $os = $_.Name
      $_.File | Copy-Item -Destination $dst[$os]
    }
    

    【讨论】:

    • 如果该目录“C:\some\where\win7”不存在,我该如何创建它?我曾尝试添加 -Force 但似乎不起作用..
    • @AutDev 如有疑问,请阅读documentation。文件夹可以通过New-Item -Type Directory创建。
    猜你喜欢
    • 2016-03-09
    • 1970-01-01
    • 2020-08-07
    • 2019-12-27
    • 1970-01-01
    • 2020-09-11
    • 1970-01-01
    • 2016-11-30
    • 2016-01-27
    相关资源
    最近更新 更多