.CSV from a .XML with PS

GianniGini 1 Reputation point
2022-10-13T05:47:37.2+00:00

Hello everyone,

I am new to powershell and I was practicing some scripts found on the net.
I found this which converts .XML files to .CSV but it doesn't work for me.

Script:

$xmlFile = Get-Content -Path C:\Users\giannigini\Desktop\test\PowerShell_Books.xml  
$xmlFile.catalog.ChildNodes | ConvertTo-Csv -NoTypeInformation -Delimiter:";" | Set-Content -Path C:\Users\giannigini\Desktop\test\PowerShell_Books_2.csv  
Get-Content -Path C:\Users\giannigini\Desktop\test\PowerShell_Books_2.csv  

Output Error:

ConvertTo-Csv : Impossibile associare l'argomento al parametro 'InputObject' perché è null.  
In riga:2 car:31  
+ ... .ChildNodes | ConvertTo-Csv -NoTypeInformation -Delimiter:";" | Set-C ...  
+                   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~  
    + CategoryInfo          : InvalidData: (:) [ConvertTo-Csv], ParameterBindingValidationException  
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ConvertToCsvCommand  
   
Get-Content : Impossibile trovare il percorso 'C:\Users\giannigini\Desktop\test\PowerShell_Books_2.csv' perché non esiste.  
In riga:3 car:1  
+ Get-Content -Path C:\Users\giannigini\Desktop\test\PowerSh ...  
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~  
    + CategoryInfo          : ObjectNotFound: (C:\Users\giann...ell_Books_2.csv:String) [Get-Content], ItemNotFoundException  
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetContentCommand  

Translation of the first row: Export-CSV Cannot bind argument to parameter because it's null

Can you explain to me what I'm doing wrong?

Thank you

Microsoft 365 and Office Development Other
Windows for business Windows Server User experience PowerShell
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Rich Matheisen 47,901 Reputation points
    2022-10-13T14:56:58.76+00:00

    The first line of your script just produces an array of strings, one string for each line in the file.

    To produce an XML document, try this:

    $xmlFile = [xml](Get-Content -Path C:\Users\giannigini\Desktop\test\PowerShell_Books.xml -Raw)  
    

    Using the "-Raw" switch on the Get-Content cmdlet results in one long string instead of an array of strings. Since XML (and HTML) don't depend on newline characters, there's no need to spend time creating an array only to cast it as XML.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.