【问题标题】:CSV import parse into xml treeCSV 导入解析到 xml 树
【发布时间】:2024-05-19 03:40:02
【问题描述】:

这个对于我的 powershell 体验来说是一个棘手的问题。如果有人可以提供帮助,那就太好了。

我有什么:

$csvdata = Import-CSV 'file.csv'

|  Location             | Description
| /Texas/Bryan          | Pond Anup
| /Texas/Bryan          | Pond Charlie
| /Texas/Killen/        | Lake Snoopy

示例:output.xml

<groups>
    <group name="Texas">
        <site name="Bryan">Pond Anup</site>
    </group>
</groups>

我要做的是循环导入 csv 并执行以下操作:

  • 如果德州不存在,则创建
  • 如果德克萨斯确实存在,但不存在 Bryan,则以 Bryan 的身份创建德克萨斯的孩子
  • 如果两者都存在,则将子节点添加到 Bryan 作为站点节点

我是 powershell 新手,这与 AD 无关,因为我看到了很多例子。我希望已经创建了一个脚本或我可以调用的 cmdlet。

谢谢

【问题讨论】:

    标签: powershell csv export-to-csv powershell-ise


    【解决方案1】:

    这是完成此操作所需的基本循环和逻辑:

    $csvdata = Import-CSV "file.csv"
    $outfile = "output.xml"
    
    "<groups>" | Out-File $outfile #start groups
    
    $lastGroup = ""
    $lastSite = ""
    
    $csvdata | foreach {
        $group = ($_.Location.Split('/'))[1]
        $site = ($_.Location.Split('/'))[2]
        $child = $_.Description
        if ($group -ne $lastGroup) #if we're not in the same group
        {
            if ($lastGroup -ne "") {"    </group>" | Out-File $outfile -Append }
            "    <group name=`"" + $group + "`">" | Out-File $outfile -Append
        }
        if ($site -ne $lastSite) #if we're not in the same site
        {
            if ($lastSite -ne "") {"        </site>" | Out-File $outfile -Append}
            "        <site name=`"" + $site + "`">" | Out-File $outfile -Append
        }
        # now write child:
        "            <child name=`"" + $child + "`"></child>" | Out-File $outfile -Append
    
        $lastGroup = $group
        $lastSite = $site
    }
    #write final end tags
    "        </site>" | Out-File $outfile -Append
    "    </group>" | Out-File $outfile -Append 
    "</groups>" | Out-File $outfile -Append #end groups
    

    代码会给你这样的输出:

    <groups>
        <group name="Texas">
            <site name="Bryan">
                <child name="Pond Anup"></child>
                <child name="Pond Charlie"></child>
            </site>
            <site name="Killen">
                <child name="Lake Snoopy"></child>
            </site>
        </group>
    </groups>
    

    希望这能让你朝着正确的方向开始。

    【讨论】: