powershell
  • ftp
  • webclient
  • 2016-09-09 100 views -2 likes 
    -2

    我在Stackoverflow上找到了此代碼,以使用Powershell從FTP站點獲取文件。 它工作的很好,那麼我想要做的只是從FPT網站下載文件後刪除它們。 有沒有一個容易修改這個腳本來做到這一點? 感謝使用Webclient和PowerShell刪除FTP站點上的文件

    #FTP Server Information - SET VARIABLES 
    $ftp = "ftp://XXX.com/" 
    $user = 'UserName' 
    $pass = 'Password' 
    $folder = 'FTP_Folder' 
    $target = "C:\Folder\Folder1\" 
    
    #SET CREDENTIALS 
    $credentials = new-object System.Net.NetworkCredential($user, $pass) 
    
    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() 
        $reader.ReadToEnd() 
        $reader.Close() 
        $response.Close() 
    } 
    
    #SET FOLDER PATH 
    $folderPath= $ftp + "/" + $folder + "/" 
    
    $Allfiles=Get-FTPDir -url $folderPath -credentials $credentials 
    $files = ($Allfiles -split "`r`n") 
    
    $files 
    
    $webclient = New-Object System.Net.WebClient 
    $webclient.Credentials = New-Object System.Net.NetworkCredential($user,$pass) 
    $counter = 0 
    foreach ($file in ($files | where {$_ -like "*.txt"})){ 
        $source=$folderPath + $file 
        $destination = $target + $file 
        $webclient.DownloadFile($source, $target+$file) 
    
        #PRINT FILE NAME AND COUNTER 
        $counter++ 
        $counter 
        $source 
    } 
    
    +1

    是的,有。但這不是一個代碼寫入服務。我們修復(也許)你寫的東西,而不是寫給你。 –

    回答

    1

    如前所述別人,這不是一個代碼編寫的服務,但這裏有一個提示。你的方法是[System.Net.WebRequestMethods+FTP]::ListDirectory。看到這裏還有什麼其他方法可用:https://msdn.microsoft.com/en-us/library/system.net.webrequestmethods.ftp(v=vs.110).aspx

    +0

    謝謝安德烈,那就是我需要的。 –

    +0

    接受答案然後 –

    2

    我創建了一個新的功能做的刪除後,我得到的每個文件

    function Del-File($url,$credentials) { 
        $request2 = [Net.WebRequest]::Create($url) 
        $request2.Method = [System.Net.WebRequestMethods+FTP]::DeleteFile 
        if ($credentials) { $request2.Credentials = $credentials } 
        $response2 = $request2.GetResponse() 
    } 
    
    +0

    好的贖回! +1 – Gaspa79

    相關問題