Home > Blockchain >  Splitting an array to different variables
Splitting an array to different variables

Time:01-21

I have an XML file with multiple same-name fields like this:

<XMLDAT>
    <Interpret>Crow Jonathan</Interpret>
    <Interpret>Mcnabney Douglas</Interpret>
    <Interpret>Haimovitz Matt</Interpret>
    <Interpret>Sitkovetski Dmitri</Interpret>
</XMLDAT>

I'm trying to split these into a separate variable for each Interpret so I can be able to export it as a CSV file. Ex.

[xml]$XML = Get-Content -Path C:\TestFile.xml

$Interpret = $XML.XMLDAT.Interpret

$interpret1 = ""
$interpret2 = ""
$interpret3 = ""
$interpret4 = ""

$DATACOLLECTION = @()

$DATA = New-Object PSObject
Add-Member -inputObject $DATA -memberType NoteProperty -name "Interpret1" -value $interpret1
Add-Member -inputObject $DATA -memberType NoteProperty -name "Interpret2" -value $interpret2
Add-Member -inputObject $DATA -memberType NoteProperty -name "Interpret3" -value $interpret3
Add-Member -inputObject $DATA -memberType NoteProperty -name "Interpret4" -value $interpret4
$DATACOLLECTION  = $DATA

$DATACOLLECTION | Export-Csv -append -path C:\test.csv -NoTypeInformation

I'm not sure how to proceed into splitting these into their own variables.

CodePudding user response:

PowerShell supports multi-target variable assignments:

[xml]$XML = Get-Content -Path C:\TestFile.xml

$interpret1, $interpret2, $interpret3, $interpret4 = $XML.XMLDAT.Interpret

But you don't really need all those variables :)

You could construct the final object by dynamically adding all the "Interpret" node values to a hashtable and then convert that to an object:

[xml]$XML = Get-Content -Path C:\TestFile.xml

$properties = [ordered]@{}

$XML.XMLDAT.Interpret |ForEach-Object -Begin {$number = 1} -Process {
    $properties["Interpret$($number  )"] = "$_"
}

@( [pscustomobject]$properties ) |Export-Csv -Append -Path C:\test.csv -NoTypeInformation

CodePudding user response:

Was able to get desired result using this ForEach loop:

ForEach ($Interprets in $Interpret){
   $interpret1 = $Interpret[0]
   $interpret2 = $Interpret[1]
   $interpret3 = $Interpret[2]
   $interpret4 = $Interpret[3]
   }

CodePudding user response:

I would just do one column with four rows:

$xml.xmldat.interpret | % { [pscustomobject]@{Interpret = $_} } 

Interpret
---------
Crow Jonathan
Mcnabney Douglas
Haimovitz Matt
Sitkovetski Dmitri
  • Related