What's the best way to automate secure FTP in PowerShell?

前端 未结 9 1617
闹比i
闹比i 2020-12-04 14:32

I\'d like to automate the FTP download of a database backup file using PowerShell. The file name includes the date so I can\'t just run the same FTP script every day. Is t

9条回答
  •  孤城傲影
    2020-12-04 15:20

    The most voted self-answer by @Eric is working, but it is:

    • inefficient with only 1KB buffer;
    • unnecessarily complicated with reimplementing, what can easily and more efficiently be done with Stream.CopyTo:
    $fileUrl = "ftp://ftp.example.com/remote/path/file.zip"
    $localFilePath = "C:\local\path\file.zip"
    
    $downloadRequest = [Net.WebRequest]::Create($fileUrl)
    $downloadRequest.Method = [System.Net.WebRequestMethods+Ftp]::DownloadFile
    $downloadRequest.Credentials =
        New-Object System.Net.NetworkCredential("username", "password")
    # Enable secure FTPS (FTP over TLS/SSL)
    $downloadRequest.EnableSsl = $True
    
    $sourceStream = $downloadRequest.GetResponse().GetResponseStream()
    $targetStream = [System.IO.File]::Create($localFilePath)
    $sourceStream.CopyTo($targetStream);
    
    $sourceStream.Dispose()
    $targetStream.Dispose()
    

    For an upload, see Upload files with FTP using PowerShell.

提交回复
热议问题