Just Code‎ > ‎

Powershell - Create Serialized XML result from database query

posted Nov 11, 2011, 1:09 AM by Peter Henell   [ updated Jan 25, 2012, 5:28 AM ]
$con = New-Object System.Data.SqlClient.SqlConnection(
"Data Source=Localhost;Initial Catalog=CustomerDb;Integrated Security=SSPI;")
function ExecuteSingleRow([string]$sql)
{
    $cmd = New-Object System.Data.SqlClient.SqlCommand($sql, $con)
    $cmd.Connection.Open()

    $adapter = New-Object System.Data.SqlClient.SqlDataAdapter($cmd)
    $ds = New-Object System.Data.DataSet
    $null = $adapter.Fill($ds)
    $row = $ds.Tables[0].Rows[0]
    $cmd.Connection.Close()
    
    $row
}
$nbp = ExecuteSingleRow "Select * from Customer where CustomerId = 5"
($nbp | ConvertTo-Xml).save("c:\temp\peter.txt")

Comments