Differences

This shows you the differences between the selected revisions of the page.

2012-03-28 2012-03-28
vb.net example (martin) powershell example (martin)
Line 222: Line 222:
End Class End Class
 +</code>
 +
 +==== PowerShell Example ====
 +<code powershell>
 +[Reflection.Assembly]::LoadFrom("WinSCP.dll") | Out-Null
 +
 +# Session.FileTransferred event handler
 +
 +function FileTransferred
 +{
 +    if ($_.Error -eq $null)
 +    {
 +        Write-Host ("Upload of {0} succeeded" -f $_.FileName)
 +    }
 +    else
 +    {
 +        Write-Host ("Upload of {0} failed: {1}" -f $_.FileName, $_.Error)
 +    }
 +
 +    if ($_.Chmod -ne $null)
 +    {
 +        if ($_.Chmod.Error -eq $null)
 +        {
 +            Write-Host ("Permisions of {0} set to {1}" -f $_.Chmod.FileName, $_.Chmod.FilePermissions)
 +        }
 +        else
 +        {
 +            Write-Host ("Setting permissions of {0} failed: {1}" -f $_.Chmod.FileName, $_.Chmod.Error)
 +        }
 +
 +    }
 +    else
 +    {
 +        Write-Host ("Permissions of {0} kept with their defaults" -f $_.Destination)
 +    }
 +
 +    if ($_.Touch -ne $null)
 +    {
 +        if ($_.Touch.Error -eq $null)
 +        {
 +            Write-Host ("Timestamp of {0} set to {1}" -f $_.Touch.FileName, $_.Touch.LastWriteTime)
 +        }
 +        else
 +        {
 +            Write-Host ("Setting timestamp of {0} failed: {1}" -f $_.Touch.FileName, $_.Touch.Error)
 +        }
 +
 +    }
 +    else
 +    {
 +        # This should never happen with Session.SynchronizeDirectories
 +        Write-Host ("Timestamp of {0} kept with its default (current time)" -f $_.Destination)
 +    }
 +}
 +
 +# Main script
 +
 +try
 +{
 +    $sessionOptions = New-Object WinSCP.SessionOptions
 +    $sessionOptions.Protocol = [WinSCP.Protocol]::Sftp
 +    $sessionOptions.HostName = "example.com"
 +    $sessionOptions.UserName = "user"
 +    $sessionOptions.Password = "mypassword"
 +    $sessionOptions.SshHostKey = "ssh-rsa 1024 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx"
 +
 +    $session = New-Object WinSCP.Session
 +    try
 +    {
 +        # Will continuously report progress of synchronization
 +        $session.add_FileTransferred( { FileTransferred } )
 +
 +        # Connect
 +        $session.Open($sessionOptions)
 +        $synchronizationResult = $session.SynchronizeDirectories(
 +            [WinSCP.SynchronizationMode]::Remote, "d:\www", "/home/martin/public_html", $false)
 +
 +        # Throw on any error
 +        $synchronizationResult.Check()
 +    }
 +    finally
 +    {
 +        $session.Dispose()
 +    }
 +
 +    exit 0
 +}
 +catch [Exception]
 +{
 +    Write-Host $_.Exception.Message
 +    exit 1
 +}
</code> </code>

Last modified: by martin