3

I'm running into a small issue trying to get the output from a stored procedure into a text file via. Powershell.

#Connection Object
$cn = New-Object System.Data.SqlClient.SqlConnection(
    "Data Source=localhost; Database=test;User ID=test;Password=xyzzy;"
    )

$q = "exec usp_Users"

#Data Adapter which will gather the data using our query
    $da = New-Object System.Data.SqlClient.SqlDataAdapter($q, $cn)
#DataSet which will hold the data we have gathered
    $ds = New-Object System.Data.DataSet
#Out-Null is used so the number of affected rows isn't printed
    $da.Fill($ds) >$null| Out-Null
#Close the database connection
$cn.Close()

if($ds.Tables[0].Rows.Count -eq 0){   
write-host '0:No Data found'   
exit 2 
}  

$file = "C:\temp\" + "users" + $(Get-Date -Format 'MM_dd_yyyy') + ".txt"
$ds.Tables[0] |  out-File $file -encoding ASCII -width 255

Here is the output:

Column1
-----
USER_NAME,USER_TYPE
[email protected],MasterAdministrator
[email protected],UserAdministrator
[email protected],Users

How can I get rid of the 'Column1' and the underline?

2 Answers 2

3

select-object with expanded property might help:

ds.Tables[0] | Select-Object -expand Column1 | out-file..
Sign up to request clarification or add additional context in comments.

Comments

0

You can export a datatable directly into a csv file by using export-csv:

$ds.Tables[0] | export-csv tofile.csv -notypeinformation

1 Comment

still leaves the 'column1' header to the file. Nice to know the export-csv tag though

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.