send csv file or txt file to sftp server

  • Hello

    Can someone help me with code to send file to sftp server please:

    Here is my code:

    # SQL Server query

    $Query = "SELECT  name from tblName"

    $SqlConnection = New-Object System.Data.SqlClient.SqlConnection

    $SqlConnection.ConnectionString = "Server=CWR-PP02;Database=testdb;Integrated Security=True"

    $SqlCmd = New-Object System.Data.SqlClient.SqlCommand

    $SqlCmd.CommandText = $Query

    $SqlCmd.Connection = $SqlConnection

    $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter

    $SqlAdapter.SelectCommand = $SqlCmd

    $DataSet = New-Object System.Data.DataSet



    # Convert the DataSet to a DataTable

    $DataTable = $DataSet.Tables[0]

    # Create the text file

    $filePath = "d:\Test\Test1.txt"

    $stream = [System.IO.StreamWriter] $filePath

    # Write the headers

    $columnHeaders = $DataTable.Columns.ColumnName -join '|'


    # Write the data

    foreach ($row in $DataTable.Rows) {

    $line = [System.String]::Join("|", $row.ItemArray)



    # Close the stream



  • Thanks for posting your issue and hopefully someone will answer soon.

    This is an automated bump to increase visibility of your question.

  • Depending on the size of your dataset you may be able to use the Export-CSV command in powershell, getting to sftp requires another library though, something like WinScp.

    Powershell allows you to import compatible libraries into your script and then use objects from them. The WinScp gui will actually generate code for you to run a transfer from a sample. You then take that sample code, paste into your script and use credentials you’ve generated from ConvertTo-SecureString.

    Here’s an example from stackoverflow.

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply