sync-ftpfolder.ps1 - синхронизация файлов с FTP

Обновляет имеющиеся файлы. Загружает отсутствующие.

$FtpPath   = 'ftp://my.ftpurl.ru/docs/'
$LocalPath = 'C:\files\docs\'
$FtpLogin  = 'john77'
$FtpPass   = 'qwe123'
 
Sync-FtpFolder $ftpPath $localPath $FtpLogin $FtpPass
function Sync-FtpFolder{
    Param(
        [Parameter( Mandatory = $true )]
        [string]$ftpPathF,
        [Parameter( Mandatory = $true )]
        [string]$localPathF,
        [string]$FtpLogin = 'anonymous',
        [string]$FtpPass  = ''
    )
    function Get-FtpFileList($url){
        $WR = [Net.WebRequest]::Create($url)
        $ErrorActionPreference = 'SilentlyContinue'
        $WR.Method = [Net.WebRequestMethods+FTP]::ListDirectoryDetails
        $WR.Credentials = [Net.NetworkCredential]::new($FtpLogin,$FtpPass)
        $WRStream = $WR.GetResponse()
        $respStream = $WRStream.GetResponseStream()
        $readStream = [IO.StreamReader]::new($respStream, [Text.Encoding]::UTF8)
        return $readStream.ReadToEnd()  
    }
    function Get-FtpFileDate($url){
        $WR = [Net.WebRequest]::Create($url)
        $ErrorActionPreference = 'SilentlyContinue'
        $WR.Method = [Net.WebRequestMethods+FTP]::GetDateTimestamp
        $WR.Credentials = [Net.NetworkCredential]::new($FtpLogin,$FtpPass)
        return $WR.GetResponse().LastModified.ToUniversalTime()
    }
    function DownloadFrom-Ftp($url,$local){
        $WC.DownloadFile($url,$local)
        (Get-Item -li $local).LastWriteTime = [string](Get-FtpFileDate $url)
    }
    function UploadTo-Ftp($url,$local){
        $WC.uploadFile($url,$local)
        (Get-Item -li $local).LastWriteTime = [string](Get-FtpFileDate $url)
    }
 
    try{[string[]]$l = ((Get-FtpFileList $FtpPathF).trim()-split '\r\n').
        where{$_[0]-ne'd'}|%{($_-split':\d+\s')[1]}
    }catch{write-host $error[0] -fo red;return}
    $WC = [Net.WebClient]::new();$i=0
    $WC.Credentials = [Net.NetworkCredential]::new($FtpLogin,$FtpPass)
    $l += (gci -li $localPathF -file).name
    $list = $l.where({$_ -ne ""})|sort -u
 
    $list|ForEach{
        $FtpPath   = $ftpPathF   + $_
        $localPath = $localPathF + $_
 
        $ftpDate   = Get-FtpFileDate $FtpPath
        $localDate = (Gi -li $localPath -ea 0).LastWriteTime
 
        write-host -n ("["+ ++$i+"/"+$list.count+"]") -fo DarkGray
        if($ftpDate -lt $localDate -and $localDate){
            $_;write-host "FTP file older" -fo red
            UploadTo-Ftp $ftpPath $localPath
            write-host "Uploaded" -fo Darkgreen
        }
        elseif($ftpDate -gt $localDate -and $ftpDate){
            $_;write-host "FTP file newer" -fo red
            DownloadFrom-Ftp $ftpPath $localPath 
            write-host "Downloaded" -fo Darkgreen
        }
        else{$_;write-host "Files identical" -fo Darkgreen}""
    }
    $WC.Dispose()
}
knowledge_base/windows/powershell/sync-ftpfolder.ps1.txt · Последнее изменение: 2023/02/27 22:01 — 127.0.0.1
© 2023 knowledge base by tuduf.ru