SySx
SySx

Reputation: 51

Create destination folder on FTP server, if it does not exist yet, using WinSCP in PowerShell

I have this script and I want to transfer archive witch script created previous to the server. But on the server I want to check and create if the target folder with name of the machine ($inputID) exists or not.

$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
    Protocol = [WinSCP.Protocol]::Ftp
    HostName = "10.10.10.10"
    PortNumber = 2121
    UserName = "user"
    Password = "pass"
    FtpSecure = [WinSCP.FtpSecure]::Explicit
    TlsHostCertificateFingerprint = "-"
}

$session = New-Object WinSCP.Session

try
{
    # Connect
    $session.Open($sessionOptions)

    # Transfer files
    # Check if $inputID folder exists, if not create it.
    # After, copy the .$inputID - $Date.zip in folder > $inpudID.
    $session.PutFiles(
        "E:\logs\win\Archive\$inputID - $Date.zip", "/Public/$inputID/*").Check()
}
finally
{
    $session.Dispose()
}

Upvotes: 1

Views: 785

Answers (1)

Martin Prikryl
Martin Prikryl

Reputation: 202158

Use Session.FileExists method and Session.CreateDirectory method:

$remotePath = "/Public/$inputID"
if (!$session.FileExists($remotePath))
{
    $session.CreateDirectory($remotePath)
}

And it's more straightforward and safe to use Session.PutFileToDirectory:

$session.PutFileToDirectory(
    "E:\logs\win\Archive\$inputID - $Date.zip", $remotePath)

Upvotes: 1

Related Questions