1

I am writing a PowerShell script which will be executed at timely intervals, which will grab any content of a specific directory + sub-directories and upload a copy of it, to an FTP server.

In case file already exist on the server, it will overwrite.
In case the directory does not exist on the server, it will be created.

I have achieved most of what I need it to do but am stuck on the sub-directory creation if not exist part.

The code I have is this, although not really clean yet.

function UploadFilesInDirectory($RemoteDestination, $LocalSource) {
    $local_files = Get-ChildItem $LocalSource

    foreach ($local_file in $local_files)
    {
        $isDirectory = (Get-Item $local_file.FullName) -is [System.IO.DirectoryInfo]

        if ($isDirectory) 
        {
            UploadFilesInDirectory -RemoteDestination "$RemoteDestination" -LocalSource "$LocalSource\$local_file"
        } 
        else 
        {
            Write-Host "Uploading $local_file"

            $desinationPath = $LocalSource.Replace("$local_backup\", "")
            $desinationPath = "$remote_connection$desinationPath\$local_file".Replace("\", "/")

            $webclient.UploadFile("$desinationPath", $file.FullName )   
        }
    }
}

Any help will be appreciated.

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
Clayton C
  • 531
  • 1
  • 4
  • 19
  • Look at [this](https://gist.github.com/dkittell/f029b6c7d1c46ebcffcb) example. – nemze May 16 '19 at 12:58
  • Is there another way though, as I prefer to not use try catch statements? – Clayton C May 16 '19 at 13:32
  • So ask a question on *"creating directory if it does not exist without using try catch statements"* and not a broad question as you did. – Martin Prikryl May 18 '19 at 09:57
  • @MartinPrikryl I was replying to nemze comment, at time of creating this question I was not aware that try catch can be used to check ftp directory existence. – Clayton C May 19 '19 at 10:04

1 Answers1

1

I do not think it's possible to effectively check for FTP directory/file existence with plain .NET/PowerShell functionality without using try/catch.

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
  • 1
    Thanks for this, I'll have a look at the first 2 options you provided as these are more interesting for my needs, especially that 2nd option. Thanks! – Clayton C May 20 '19 at 08:54