powershell-ftpmove文件到本地

#FTP Server Information - SET VARIABLES
$ftp = "ftp://172.20.168.x"
$user = "gg"
$pass = "xxx"
$folder = "down"
$target = "D:\111\"

#Register get FTP Directory function
function Get-FtpDir ($url, $credentials) {
    $request = [Net.WebRequest]::Create($url)
    $request.Method = [System.Net.WebRequestMethods+FTP]::ListDirectory
    if ($credentials) { $request.Credentials = $credentials }
    $response = $request.GetResponse()
    $reader = New-Object IO.StreamReader $response.GetResponseStream() 
    while(-not $reader.EndOfStream) {
        $reader.ReadLine()
    }
    $reader.Close()
    $response.Close()
}


#Register Delete function
function Del-FtpFile($source, $credentials) {
    $source2 = [system.URI] $source
    $ftp = [System.Net.FtpWebRequest]::create($source2)
    $ftp.Credentials = $credentials
    $ftp.Method = [System.Net.WebRequestMethods+Ftp]::DeleteFile
    $ftp.GetResponse()
}

#Set Crednetials
$credentials = new-object System.Net.NetworkCredential($user, $pass)

#set folder path
$folderPath= $ftp + "/" + $folder + "/"
Write-Host $folderPath
$files = Get-FTPDir -url $folderPath -credentials $credentials
$webclient = New-Object System.Net.WebClient
$webclient.Credentials = $credentials
$counter = 0
foreach ($file in ($files | where {$_ -like "*.txt"})){
    $source = $folderPath + $file
    $destination = $target + $file
    $webclient.DownloadFile($source, $destination)
    #PRINT FILE NAME AND COUNTER
    $counter++
    $source
    # DELETE FILE
    Del-FtpFile -source $source -credentials $credentials
}

 

posted @ 2020-10-27 13:39  JinweiChang  阅读(138)  评论(0编辑  收藏  举报