使用 Webclient 和 powershell 删除 FTP 站点上的文件

Delete files on FTP site using Webclient and powershell

我在 Whosebug 上找到了这段代码,可以使用 Powershell 从 FTP 站点获取文件。 它工作得很好,然后我唯一想做的就是在下载文件后从 FPT 站点删除文件。 这个脚本有一个简单的修改来做到这一点吗? 谢谢

  #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
}

正如其他人所说,这不是代码编写服务,但这里有一个提示。您的方法是 [System.Net.WebRequestMethods+FTP]::ListDirectory。在这里查看还有哪些其他方法可用:https://msdn.microsoft.com/en-us/library/system.net.webrequestmethods.ftp(v=vs.110).aspx

我创建了一个新函数来在获取每个文件后进行删除

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()
}