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

Time:07-15

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()
}

CodePudding user response:

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)
  • Related