2016-09-09 2 views
0

Nun, dieses ist eine knifflige für meine Powershell-Erfahrung. Wenn jemand helfen kann, wäre das toll.CSV-Import in xml-Baum parsen

Was ich habe:

$csvdata = Import-CSV 'file.csv' 

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

Beispiel: output.xml

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

Was ich versuche, durch den CSV-Import zu tun ist, Schleife und wie folgt vor:

  • Wenn Texas nicht existiert, erstellen Sie
  • Wenn Texas existiert aber nicht Bryan create c Hild nach Texas als Bryan
  • Wenn beide existieren Kind als Standortknoten

Ich bin neu in Powershell zu Bryan hinzufügen und das hat nichts mit AD zu tun, wie ich viele Beispiele gibt für diese gesehen. Ich hoffe, dass ein Skript bereits erstellt wurde oder ein Cmdlet, das ich aufrufen kann.

Dank

Antwort

0

Hier ist die grundlegende Schleife und Logik, die Sie verwenden müssen, würde dies zu tun:

$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 

Der Code wird Ihnen Ausgabe wie folgt geben:

<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> 

Hoffentlich Das bringt dich in die richtige Richtung.