Custom directory listing format (CSV)

You may want to output a directory listing from WinSCP to a file with custom format that you can further process by another application.

The following examples produce a tab-delimited CSV file that can be imported to Microsoft Excel.

Using WinSCP .NET Assembly

The following example uses WinSCP .NET assembly from a PowerShell script. If you have another preferred language, you can easily translate it.

param (
    $sessionUrl = "sftp://user:mypassword;",
    $remotePath = "/path",
    $outFile = "listing.csv"
    # Load WinSCP .NET assembly
    Add-Type -Path "WinSCPnet.dll"
    # Setup session options
    $sessionOptions = New-Object WinSCP.SessionOptions
        # Connect
        Write-Host "Connecting..."
        $session = New-Object WinSCP.Session
        # Retrieve listing
        Write-Host "Listing..."
        $directory = $session.ListDirectory($remotePath)
        # Remove output file if it exists
        if (Test-Path $outFile)
            Remove-Item $outFile
        # Generate a custom listing for each file in the output file
        # Using UTF-16 (Unicode) encoding that Microsoft Excel likes.
        foreach ($fileInfo in $directory.Files)
            ("`"{0}`"`t{1}`t`"{2}`"" -f $fileInfo.Name, $fileInfo.Length, $fileInfo.LastWriteTime) | Out-File -Append $outFile -Encoding Unicode
        Write-Host "Done"
        # Disconnect, clean up
    exit 0
catch [Exception]
    Write-Host ("Error: {0}" -f $_.Exception.Message)
    exit 1

Using WinSCP Scripting

You may have WinSCP produce XML log with the listing and convert it to your custom format using XSLT:

Use the following Windows batch file (listing.bat):

@echo off
set XMLLOG=script.xml /log=script.log /xmllog=%XMLLOG% /command ^
    "open mysession" ^
    "ls /path" ^
if %ERRORLEVEL% == 0 msxsl.exe %XMLLOG% listing.xsl > listing.csv

Where the listing.xsl may look like:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="" xmlns:winscp="">
    <!-- Using UTF-16 encoding that Microsoft Excel likes -->
    <xsl:output method="text" encoding="UTF-16"/>
    <xsl:strip-space elements="*"/>
    <xsl:template match='winscp:ls[winscp:result[@success="true"]]/winscp:files/winscp:file'>
         <xsl:value-of select="winscp:filename/@value"/>
         <xsl:value-of select="winscp:size/@value"/>
         <xsl:value-of select="winscp:modification/@value"/>

Further Reading

  script_custom_listing_format_csv.txt · Last modified: by martin

Search Documentation

This page


About donations

$9   $19   $49   $99

About donations



Site design by Black Gate