0

Below is my PowerShell script that connects to a remote SQL server and stored the result into a XML file.

$SQLResult = Invoke-Sqlcmd -inputfile $inputfile -ServerInstance $ServerInstance -Database $Database -Username $Username -Password $Password 
$PropertyName = ($SQLResult | Get-Member -MemberType Property | Where {$_.Name -like "XML*"}).Name
$SQLResult.$PropertyName | Out-File -FilePath "C:\Temp\ExportFile.xml" -Force

Ideally it should return sth clean and neat like this (Which is also the case when I open up the result in my SQL Server Management Studio):

<Text>
    <Data>I am happy</Data>
</Text>

However, when I open the file, it gives me:

<Text><Data>I am happy</Data></Text>

I have tried to use Export-Clixml, but the XML returned is surrounded by some meaningless tags called <props> which is not one of my tags.

Can anyone help me out on this, not sure which way to go to save it in its original format.

1

1 Answer 1

2

Use an XmlWriter to format and indent it nicely when writing back to disk:

# Create settings object, make sure we get the indentation
$writerSettings = [System.Xml.XmlWriterSettings]::new()
$writerSettings.Indent = $true

try{
  # Create the writer
  $writer = [System.Xml.XmlWriter]::Create("C:\Temp\ExportFile.xml", $writerSettings)

  # Convert your XML string to an XmlDocument, 
  # then save the document using the writer
  ([xml]$SQLResult.$PropertyName).Save($writer)
}
finally {
  # discard writer (closes the file handle as well)
  $writer.Dispose()
}
Sign up to request clarification or add additional context in comments.

5 Comments

I tried this but it returns an error: Cannot convert value "System.Object[]" to type "System.Xml.XmlDocument". Error: "'>' is an unexpected token. The expected token is '='. Line 3, position 3."
@David Sounds like whatever string value $SQLResult.$PropertyName resolved to isn't valid XML :)
Is there a way to see if anything is wrong with my XML file :( rly have no clue
@David If you just print/output the value of $SQLResult.$Property to the screen, what's on line 3?
PS C:\Users\David Kao> $SQLResult.$Property PS C:\Users\David Kao>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.