我在Stackoverflow上发现了这个代码,使用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
}
答案 0 :(得分:3)
正如其他人所说,这不是代码编写服务,但这里有一个提示。您的方法是[System.Net.WebRequestMethods+FTP]::ListDirectory
。请在此处查看其他可用方法:https://msdn.microsoft.com/en-us/library/system.net.webrequestmethods.ftp(v=vs.110).aspx
答案 1 :(得分:3)
我创建了一个新函数来在获取每个文件后进行删除
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()
}