I turned your PS into a function, just changing the calls, ran it through the PS ISE, and it worked just fine for me in testing, outputting the data to the location. I would ensure that you have the ability to write to the root of the C: drive. Typically this can require admin permissions. It's possible you are swallowing the error somewhere.
function ProcToXmlFile {
param
(
[string]$outputType,
[string]$filename
)
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=localhost;Database=master;Integrated Security=True"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = "select name from sys.databases for XML AUTO"
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$SqlConnection.Close()
$DataSet.Tables[0]
if ($outputType -eq "Text")
{
$DataSet.Tables[0] | format-table -auto > $filename
}
if ($outputType -eq "xml")
{
$DataSet.Tables[0] |Export-Clixml $filename
}
}
ProcToXmlFile "xml" "c:\temp\test.xml"
Created the file in the correct location with the contents:
<Objs Version="1.1.0.1" xmlns="http://schemas.microsoft.com/powershell/2004/04">
<Obj RefId="0">
<TN RefId="0">
<T>System.Data.DataRow</T>
<T>System.Object</T>
</TN>
<ToString>System.Data.DataRow</ToString>
<Props>
<S N="XML_F52E2B61-18A1-11d1-B105-00805F49916B"><sys.databases name="master"/><sys.databases name="tempdb"/><sys.databases name="model"/><sys.databases name="msdb"/><sys.databases name="HealthCheck"/><sys.databases name="RestoreAttachTEST"/></S>
</Props>
</Obj>
</Objs>
Here's an updated version (a little hacky, I know) that writes the header to a file, and then just the XML data that is produced. See if this gets you a little closer.
function ProcToXmlFile {
param
(
[string]$outputType,
[string]$filename
)
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=localhost\sql16;Database=master;Integrated Security=True"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = "select name from sys.databases for XML AUTO"
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$SqlConnection.Close()
$DataSet.Tables[0] | Format-Wide -AutoSize
$Headerstring = '<?xml version="1.0" encoding="UTF-8?>'
$Headerstring | Out-File $filename
if ($outputType -eq "Text")
{
$DataSet.Tables[0] | Format-Table -HideTableHeaders | out-file $filename -Width 5000 -Append
}
if ($outputType -eq "xml")
{
$DataSet.Tables[0] |Export-Clixml $filename
}
}
ProcToXmlFile "text" "c:\temp\test.xml"